Mastering C++ STL Vectors

Objective

  • Understand the purpose and advantages of using vector.
  • Learn common operations (insertion, deletion, traversal, etc.).
  • Practice advanced features like iterators and algorithms.

1. Introduction to Vectors (15 minutes)

Concepts

  • Definition: vector is a dynamic array that can resize automatically.
  • Header File: <vector>.
  • Advantages over C-style arrays:
    • Dynamic resizing.
    • Easier memory management.
    • Rich set of member functions.

Code Demo

#include 
#include
using namespace std;

int main() {
// Creating a vector
vector numbers;

// Adding elements
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

// Displaying elements
cout << "Vector elements: ";
for (int num : numbers) {
cout << num << " ";
}

return 0;
}

2. Basic Operations (30 minutes)

Key Operations

  1. Initialization
    vector<int> vec1; // Empty vector vector<int> vec2(5, 10); // Size 5, all elements = 10 vector<int> vec3 = {1, 2, 3, 4}; // List initialization
  2. Adding/Removing Elements
    • push_back(value): Adds an element at the end.
    • pop_back(): Removes the last element.
    • insert(iterator, value): Inserts an element at a specified position.
    • erase(iterator): Removes an element at a specified position.
  3. Accessing Elements
    • vec[index] or vec.at(index).
    • Front and back elements: front() and back().

Code Demo

#include 
#include

int main() {
vector vec = {1, 2, 3, 4, 5};

// Adding and removing elements
vec.push_back(6);
vec.pop_back();

// Accessing elements
cout << "First element: " << vec.front() << "\n";
cout << "Last element: " << vec.back() << "\n";

// Modifying an element
vec[2] = 10;

// Display the vector
for (int num : vec) {
cout << num << " ";
}

return 0;
}

Exercise 1

  • Create a vector of strings to store names.
  • Add 5 names, remove the last one, and print the vector.

3. Traversing Vectors (20 minutes)

Methods

  1. Using Indexing
    for (size_t i = 0; i < vec.size(); ++i) { cout << vec[i] << " "; }
  2. Using Range-based For Loop
    for (int num : vec) { cout << num << " "; }
  3. Using Iterators}for (auto it = vec.begin(); it != vec.end(); ++it) { cout << *it << " "; }

Code Demo

#include 
#include

int main() {
vector vec = {10, 20, 30, 40};

cout << "Using indexing: ";
for (size_t i = 0; i < vec.size(); ++i) {
cout << vec[i] << " ";
}

cout << "\nUsing range-based loop: ";
for (int num : vec) {
cout << num << " ";
}

cout << "\nUsing iterators: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}

return 0;
}

Exercise 2

  • Write a program to traverse a vector of floating-point numbers using all three methods.

4. Advanced Features (30 minutes)

Sorting and Algorithms

  • sort(vec.begin(), vec.end()): Sorts in ascending order.
  • reverse(vec.begin(), vec.end()): Reverses the vector.
  • Use <algorithm> for STL functions.

Code Demo

#include 
#include
#include // For sort and reverse

int main() {
vector vec = {40, 10, 30, 20};

// Sorting
sort(vec.begin(), vec.end());
cout << "Sorted: ";
for (int num : vec) cout << num << " ";

// Reversing
reverse(vec.begin(), vec.end());
cout << "\nReversed: ";
for (int num : vec) cout << num << " ";

return 0;
}

Exercise 3

  • Create a vector of integers.
  • Sort the vector in descending order and display it.

5. Common Pitfalls and Debugging Tips (10 minutes)

  1. Accessing Out-of-Bounds Elements
    • Use at(index) to avoid undefined behavior.
    • Example:
      cout << vec.at(10); // Throws an exception if index is invalid.
  2. Resizing and Capacity
    • vec.size() vs. vec.capacity().
    • Use vec.resize(new_size) to change the size.

Code Demo

#include 
#include

int main() {
vector vec = {1, 2, 3};

// Capacity vs size
cout << "Size: " << vec.size() << "\n";
cout << "Capacity: " << vec.capacity() << "\n";

// Resizing
vec.resize(5);
cout << "After resizing, size: " << vec.size() << "\n";

return 0;
}

Exercise 4

  • Experiment with resizing a vector and observing its behavior.

6. Final Project (15 minutes)

Task

Write a program that:

  1. Reads integers from the user into a vector.
  2. Sorts the vector.
  3. Removes all duplicate elements.
  4. Displays the final vector.

Hint

Use unique and erase.


7. Q&A and Recap (10 minutes)

  • Revisit the advantages of vectors.
  • Clarify any questions.
  • Discuss real-world use cases of vectors in applications.

This tutorial covers both basic and advanced concepts with hands-on exercises, ensuring students understand the functionality and versatility of STL vectors in C++.

Scroll to Top