TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 12 of 18 · Free

Vectors & Iterators in C++ – Grow, Search, Insert and Erase

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Use size, capacity, reserve, front, back and pop_back on a vector
  • Walk through a vector with iterators and use them with find and sort
  • Insert and erase elements safely, including the erase-remove idiom

A cricket scorer does not know before the match how many balls will be bowled. A plain array needs a fixed size, but a vector grows as you go. In Lesson 5 you used vectors. Now you learn how they work inside, and how iterators let you walk through, search and change them.

What is a vector in C++ and why not use an array?

A vector (header <vector>) is a list that can grow and shrink while the program runs. A plain array like int a[5] has a fixed size forever.

push_back adds at the end, pop_back removes the last element, front() and back() give the first and last, and size() tells how many there are.

The vector frees its own memory when it is destroyed, so you never call delete. Try it: push_back one more score and run again.

🧩 C++ — you can edit this code
Output
Balls: 4
First ball: 4
Last ball: 1
After pop_back: 3 balls, 10 runs
Empty? no

What is the difference between size and capacity of a C++ vector?

size() is how many elements the vector holds. capacity() is how many it can hold before it must find a bigger block of memory.

When the space runs out, the vector gets a bigger block, copies everything across and frees the old block. That copying takes time.

If you know roughly how many items will come, call reserve(n) first. reserve changes capacity, NOT size. The exact growth steps depend on the library; the numbers below are from this compiler.

🧩 C++ — you can edit this code
Output
size 1, capacity 1
size 2, capacity 2
size 3, capacity 4
size 4, capacity 4
size 5, capacity 8
After reserve: size 0, capacity 40
vector<int> zeros(3) has size 3

What is an iterator in C++?

An iterator is an object that points to one element of a container. Think of it as a bookmark you can move along the list.

begin() points to the first element. end() points just AFTER the last one, so it is a stop sign, not an element. *it gives the element, ++it moves to the next.

Writing the type vector<int>::iterator is long, so most people write auto. For a vector, it - v.begin() gives the position (index).

🧩 C++ — you can edit this code
Output
Riya Aman Sara Kabir 
0:Riya 1:Aman 2:Sara 3:Kabir 
Kabir! Sara! Aman! Riya! 

💡 rbegin() and rend() are reverse iterators: ++ moves them backwards through the vector.

How do you insert and erase elements in a C++ vector?

insert(it, value) puts a value BEFORE the position it points to. erase(it) removes the element at that position. Both take iterators, not plain numbers.

To use an index, add it to begin(): v.begin() + 2 means position 2. All the elements after that point shift along.

erase returns an iterator to the element that came after the removed one. Use that returned iterator when you erase inside a loop. Try it: change the loop to remove marks below 50.

🧩 C++ — you can edit this code
Output
72 60 30 85 28 91 
60 30 85 28 91 
60 85 91 

How do iterators work with find, sort and other C++ algorithms?

The algorithms in <algorithm> (Lesson 5) all take a range: a begin iterator and an end iterator. That is why the same sort works on vectors, arrays and more.

find returns an iterator to the first match, or end() when there is none. Always compare with end() before using *it.

remove_if does NOT shrink the vector. It moves the kept elements to the front and returns where the leftovers start. erase then cuts them off. This pair is called the erase-remove idiom.

🧩 C++ — you can edit this code
Output
78 found at position 2
Best: 101
Ducks: 2
101 78 45 33 12 

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

vector<int> v = {10, 20, 30};
v.insert(v.begin() + 1, 15);
v.pop_back();
for (int x : v) {
    cout << x << " ";
}
cout << "\n";

Question 2. 16 is not in the vector. What does this print?

vector<int> v = {4, 8, 15};
auto it = find(v.begin(), v.end(), 16);
cout << (it - v.begin()) << "\n";

Question 3. What does this print?

vector<int> v;
v.reserve(10);
cout << v.size() << " " << (v.capacity() >= 10) << "\n";

🧩 Your challenge

A class test has these marks: 56, 23, 89, 34, 72, 91, 18, 65. Using iterators and algorithms: (1) print the position of the first mark below 35 (use find_if), (2) remove every mark below 35 with the erase-remove idiom, (3) sort the rest from highest to lowest and print them, (4) print how many passed. Expected output: First fail at position 1 Passed marks: 91 89 72 65 56 Passed: 5

Expected output :
First fail at position 1
Passed marks: 91 89 72 65 56
Passed: 5
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

vector<int> v = {5, 10, 15};
auto it = find(v.begin(), v.end(), 10);
cout << it << "\n";

Line 3: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::__wrap_iter<int *>')

✅ Right

vector<int> v = {5, 10, 15};
auto it = find(v.begin(), v.end(), 10);
cout << *it << "\n";

An iterator is a position, not the value. cout cannot print it. Use *it to get the element.

❌ Wrong

vector<int> v = {7, 0, 3, 0};
remove(v.begin(), v.end(), 0);
cout << "Size: " << v.size() << "\n";

Compiles and runs, but prints: Size: 4 ⏎

✅ Right

vector<int> v = {7, 0, 3, 0};
v.erase(remove(v.begin(), v.end(), 0), v.end());
cout << "Size: " << v.size() << "\n";

remove only moves the kept values to the front; the vector keeps its size. Pass its result to erase to really delete the leftovers.

❌ Wrong

vector<int> fees = {1000, 1200, 1500};
for (auto f : fees) {
    f += 100;
}
cout << fees[0] << "\n";

Compiles and runs, but prints: 1000 ⏎

✅ Right

vector<int> fees = {1000, 1200, 1500};
for (auto& f : fees) {
    f += 100;
}
cout << fees[0] << "\n";

auto f makes a copy of each element, so the vector does not change. Use auto& f to change the real elements.

📌 Remember

  • A vector grows and shrinks; size() counts elements, capacity() counts room.
  • reserve(n) makes room without adding elements.
  • begin() points to the first element, end() to one past the last; *it gives the value.
  • insert and erase take iterators; use the iterator erase returns inside loops.
  • find returns end() when nothing matches — check before using *it.
  • remove / remove_if must be followed by erase (the erase-remove idiom).

Finished the quiz and the challenge?

Questions students ask

What is the difference between an array and a vector in C++?

An array has a fixed size set when you write the code. A vector can change size while the program runs and manages its own memory. Both store elements next to each other, so both are fast to index.

What does end() point to in C++?

end() points one place past the last element. It is a stop marker for loops, so you must never use *v.end().

When should I use iterators instead of an index?

Use iterators with STL algorithms and with containers like list, set and map, which have no [] index. For simple vector loops, an index or a range-based for loop is fine.

Why did my iterator stop working after push_back?

If push_back needs more capacity, the vector moves to a new block of memory. Old iterators then point to freed memory and must not be used. Get fresh iterators after adding or erasing.