How to iterate through a vector in C++

Key takeaways

  • Vector: Vectors are dynamic arrays that can grow in size, offering more flexibility than static arrays.

  • Iteration methods:

    • Range-based for loops (C++11+) simplify iteration and are ideal for read-only access.

    • Traditional for loop and indexes are useful for index-based operations.

    • Use iterator for fine-grained control.

    • Use the auto keyword to reduce type errors.

    • Use constant iterators (cbegin() and cend()) to ensure that elements are not modified.

  • Practical applications: Iteration techniques can be used in data analysis, game development, packet processing, etc.

Understanding how to iterate over a vector is a key skill in the C++ programming language. It has multiple practical applications across various domains. Here are some practical examples of iterating over a vector.

  • Data analysis: Iterating vector of age data to calculate averages.

  • Game development: Iterating vector of game objects to apply updates or changes.

  • Searching: Iterating vector of elements to find specific items.

  • Packet processing: Iterating vector of network packets to handle or process them.

Vectors in C++

The Standard Library offers multiple containers for C++ programming, including arrays, vectors, and lists. This library simplifies code, enhances clarity and performance, and reduces maintenance issues. As Bjarne Stroustrup, the creator of C++, acknowledges:

“The standard library saves programmers from having to reinvent the wheel.”

Vectors is one of the useful data structures in C++ that act like dynamic one-dimensional arrays.

Syntax

vector<int> vec = {1, 2, 3, 4, 5};

Code examples for iterating vector in C++

In this Answer, we’ll explore five different methods to iterate through a vector in C++, as listed below:

1. Use a range-based for loop (C++11 and later)

Range-based for loops were introduced in C++11, which simplifies the syntax by abstracting away the need for manual indexing or iterators used by traditional for loops.

#include <iostream>
#include <vector>
using namespace std;
int main() {
// Declaration of int vector
vector<int> vec = {1, 2, 3, 4, 5};
// Corrected range-based for loop
for (int num : vec) {
cout << num << " ";
}
cout << std::endl;
return 0;
}

2. Use a traditional for loop and indexing

In C++, vectors can be indexed with []operator, similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec.size().

#include <iostream>
#include <vector>
using namespace std;
int main()
{
//Declaration of int vector
vector<int> vec = {1, 2, 3, 4, 5};
// Returns length of vector as unsigned int
unsigned int vecSize = vec.size();
// Run for loop from 0 to vecSize
for(unsigned int i = 0; i < vecSize; i++)
{
cout << vec[i] << " ";
}
cout << endl;
return 0;
}

Note: Instead of the []operator, the at() function can also be used to fetch the value of a vector at a specific index:

vec.at(i)
  • Where i is the index.

3. Use an iterator

An iterator can be generated to traverse through a vector.


vector<int>::iterator iter;

An iterator is used as a pointer to iterate through a sequence, such as a string or vector. The pointer can then be incremented to access the next element in the sequence. To access the value in the memory space to which the iterator is pointing, you must use *.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
//Declaration of int vector
vector<int> vec = {1, 2, 3, 4, 5};
int vecSize = vec.size(); // returns length of vector
//Declaration of vector iterator
vector<int>::iterator iter = vec.begin();
cout << "Vector: ";
// Run for loop from 0 to vecSize
for(iter; iter < vec.end(); iter++)
{
// Access value in the memory to which the pointer
// is referencing
cout << *iter << " ";
}
cout << endl;
return 0;
}

4. Use the auto keyword

The C++ auto keyword can also be used to traverse through a vector. auto must be given a variable to store the accessed element and the sequence that needs to be iterated. It must be used in conjunction with a for loop, as shown below.

#include <iostream>
#include <vector>
using namespace std;
int main() {
//Declaration of int vector
vector<int> vec = {1, 2, 3, 4, 5};
int vecSize = vec.size(); // Returns length of vector
cout << "Vector: ";
for (auto & element : vec)
{
cout << element << " ";
}
return 0;
}

5. Use a for loop with cbegin() and cend()

cbegin() and cend() are constant iterators that point to constant content. They cannot write to the element that the const element points to, but they can read from it.

cbegin() is a const iterator that points to the first element in the vector and cend() points to the past-the-endA position just after the last element of the vector. element in the vector.

#include <iostream>
#include <vector>
using namespace std;
int main() {
//Declaration of int vector
vector<int> vec = {1, 2, 3, 4, 5};
cout << "Vector: ";
// Iterating with cbegin() and cend()
for (auto it = vec.cbegin(); it != vec.cend(); ++it) {
std::cout << *it << " ";
}
return 0;
}

Quiz!

1

How to access an element using an iterator

A)

it()

B)

it[]

C)

*it

D)

it->

Question 1 of 30 attempted

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do we iterate through two equal vectors in C++?

We can iterate over two vectors in C++ using a simple for loop with indexing.

  //decleration of int vector
  vector<int> vec1 = {1, 2, 3, 4, 5};
  vector<int> vec2 = {6, 7, 8, 9, 10};

  // returns length of vector as unsigned int
  unsigned int vecSize = vec1.size();

  // run for loop from 0 to vecSize
  for(unsigned int i = 0; i < vecSize; i++)
  {
    cout << vec1[i] << " " << vec2[i] <<endl;
  }

How do we iterate through a string vector in C++?

There are multiple ways to iterate through a string vector in C++. For example, range-based for loop, traditional C++ for loop, or iterator.

vector<string> strVec = {"Educative", "Platform"};
    for (string str : strVec) {
      cout << str << std::endl;
    }

How do we access elements in vector C++ using an iterator?

We can use the dereference operator (*) to access the value of the element pointed to by the iterator.

  for(iter; iter < vec.end(); iter++)
  {
    cout << *iter << " ";
  }

Do we iterate through a vector in C++?

C++ provides multiple ways to iterate over a vector, as listed below:

  1. Use a range-based for loop  (C++11 and later)
  2. Use a traditional C++  for loop  and indexing
  3. Use an iterator
  4. Use  the auto keyword
  5. Use a C++ for loop with cbegin() and cend()

How do we print a vector in C++ using a for loop?

We can print a vector using range-based for loop:

    vector<int> vec = {1, 2, 3, 4, 5};
    for (int num : vec) {
        cout << num << " ";
    }

How do we iterate through a map in C++?

We can iterate through a C++ map in multiple ways. Here is the example using iterators:

  map<int, string> Employees; 

  //Inserting values in map using the insert function
  Employees.insert ( std::pair<int, string>(101,"Jon") );
  Employees.insert ( std::pair<int, string>(103,"Daenerys") );
  Employees.insert ( std::pair<int, string>(104,"Arya") );
  
  cout << "Size of the map is " << Employees.size() << endl << endl;  

  // Printing values in the map
  cout << endl << "Default Order of value in map:" << endl;  
  for( map<int,string>::iterator iter=Employees.begin(); iter!=Employees.end(); ++iter)  
  {  
    cout << (*iter).first << ": " << (*iter).second << endl;  
  }  

How do we print a specific element of a vector in C++?

We can access and print specific elements of the vector using the operator [] or at() method with cout statement, respectively.


Free Resources