In this article, we will discuss different ways to iterate over a vector in C++.

Watch different ways to iterate or loop over a Vector in C++.

Iterate over a vector in C++ using range based for loops

Range based for loops were introduced in C++11. It helps to loop over a container in more readable manner. Let’s see how we can use these range based for loops to iterate over a vector of integers and print each element while iteration,

#include<iostream>
#include<vector>

using namespace std;

int main()
{
    // Create a vector of integers
    vector<int> vec_of_num{1, 3, 4, 7, 8, 9};

    // Iterate over a vector using range based for loop
    for(auto & elem : vec_of_num)
    {
        cout<<elem<<", ";
    }
    return 0;
}

Output:

1, 3, 4, 7, 8, 9,

Here, we iterated over all the elements of vector and to select each element we used the auto type. The benefit of this approach is that we don’t need to specify the type of elements in vector. Also, instead of just printing them we can do other operations too with each element.

For example, let’s see how to calculate the sum of all values in a vector by iterating over the vector and add each element i.e.

#include<iostream>
#include<vector>

using namespace std;

int main()
{
    // Create a vector of integers
    vector<int> vec_of_num{1, 3, 4, 7, 8, 9};

    // Iterate over vector of integers and get sum of
    // all numbers in the vector
    int sum = 0;
    for(auto & elem : vec_of_num)
    {
        sum = sum + elem;
    }
    cout<<"Total : "<<sum ;

    return 0;
}


Output:

Total : 32

Iterate over a vector in C++ using indexing

In the previous example, we iterated over all items in vector. But during iteration we were not aware of the index positions of the elements. So, if we want to iterate over all elements of a vector through indexing, then we can use the normal for loop. For example,

#include<iostream>
#include<vector>

using namespace std;

int main()
{
    // Create a vector of integers
    vector<int> vec_of_num{1, 3, 4, 7, 8, 9};

    // Iterate over vector of integers by indexing
    for(int i = 0; i < vec_of_num.size(); i++)
    {
        cout<<vec_of_num[i]<<" at index position: "<<i <<endl;
    }

    return 0;
}

Output:

1 at index position: 0
3 at index position: 1
4 at index position: 2
7 at index position: 3
8 at index position: 4
9 at index position: 5

We iterated over the vector and while iteration printed each element along with the index position.

C++: Iterate over a vector in single line

Using STL Algorithm for_each(start, end, callback), we can iterate over all elements of a vector in a single line. It accepts three arguments i.e.

  • Start Iterator -> Iterator pointing to the start of a range
  • End Iterator -> Iterator pointing to the End of a range
  • Callback Function -> A function that needs to be applied to all elements in the range from start to end.

for_each() iterates over all the elements between start & end iterator and apply the given callback on each element.

We can pass iterators pointing to start & end of vector and a lambda function to the for_each(). It traverses through all elements of the vector and applies the passed lambda function on each element. Inside the lambda function we can perform any operation like printing the elements or
adding the elements in vector etc. Let’s see some examples,

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    // Create a vector of integers
    vector<int> vec_of_num{1, 3, 4, 7, 8, 9};

    // Iterate over a vector using STL algorithm
    // for_each() and Lambda function
    for_each(vec_of_num.begin(), 
             vec_of_num.end(),
             [](const auto & elem){
                cout<<elem<<", "; 
        });

    return 0;
}

Output:

1, 3, 4, 7, 8, 9,

Here, we applied a lambda function on each element of vector and inside the lambda function, we printed each element.

Let’s see an another example, where we will calculated the sum of all elements of a vector of integers using for_each() and a lambda function,

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    // Create a vector of integers
    vector<int> vec_of_num{1, 3, 4, 7, 8, 9};

    // Iterate over a vector of int and get the
    // sum of all itegers in the vector
    int sum = 0;
    for_each(   vec_of_num.begin(), 
                vec_of_num.end(),
                [&sum](const auto & elem){
                    sum = sum + elem;   
                });

    cout<<"Total : "<<sum ;

    return 0;
}

Output:

Total : 32

C++: Iterate over a vector using iterators

We can also use the iterators to loop over all elements of a vector. In C++, vector class provides two different functions, that returns the iterator of start & end of vector,

  • vector::begin() –> Returns an iterator that points to the start of vector,
  • vector::end() –> Returns an iterator that points to the end of vector.

We can use a while loop to traverse a vector by iterating over the elements between start and end iterators.

For example,

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    // Create a vector of integers
    vector<int> vec_of_num{1, 3, 4, 7, 8, 9};

    // Iterate over a vector of integers using iterators
    for(vector<int>::iterator   it = vec_of_num.begin();
                                it != vec_of_num.end();
                                it++ )
    {
        cout<<*it<<", ";         
    }
    
    return 0;
}

Output:

1, 3, 4, 7, 8, 9,

Summary

We can iterate over all elements of a vector using different techniques. Like range based for loops for more readability or using indexing or in a single line using STL Algorithm for_each() & Lambda Function or using the iterators.