How to Iterate Through a Vector in C++

by | C++, Programming, Tips

The simplest way to iterate through a vector using a for loop and the [] operator to index the vector. This tutorial will describe how to iterate through a vector with code examples.


Iterate Through a Vector Using Indexing

We can use the subscript [] operator to access the vector elements and a for loop to iterate over the elements. Let’s look at how to iterate over a vector of integers.

#include <iostream>
#include <vector>
int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Length of vector

    unsigned int vec_size = vec.size();
 
    // Iterate over vector using indexing

    for(unsigned int i =0; i<vec_size; i++){

        std::cout<<vec[i]<<"\n";
   
    }
   
    std::cout << std::endl;

    return 0;
}

Let’s run the code to print each element in the vector.

9
1
5
10
11
0
7
3
2
4
8

Iterate Through a Vector Using Range-based loops

Range-based loops were introduced in C++11 and provide a more readable approach to iterating over a range of values such as elements in a container. Let’s look at an example of using the range-based loops to iterate over a vector of integers and print each element:

#include <iostream>
#include <vector>
int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Range based loop

    for (auto & ele : vec) {

        std::cout << ele << "\n";

    }

    return 0;

}

Let’s run the code to print each element in the vector.

9
1
5
10
11
0
7
3
2
4
8

Iterate Through a Vector Using an iterator

We can use the auto keyword to ask the compiler to deduce the variable type from the initialization. Let’s look at an example of iterating over a vector of integers using an iterator.

#include <iostream>
#include <vector>

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Vector iterator using auto keyword

    auto it = vec.begin();

    while(it != vec.end()){

        std::cout << *it << "\n";

        it++;

    }

return 0;

}
9
1
5
10
11
0
7
3
2
4
8

Iterate Through a Vector Using for_each with Function

We can use the for_each() function, with the syntax for_each(start, end, callback), where:

  • start: iterator pointing to the start of a range
  • end: iterator pointing to the end of a range
  • callback: function applied to all elements in the range from start to end

The for_each() function iterates over all elements between start and end and applies the callback function on each element.

In our example, the callback function calls std::cout to print each element in the vector.

#include <iostream>
#include <vector>

// Define callback function

void func(int const& value){

    std::cout<<value<<"\n";

}

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Iterate through vector using for_each() with callback function

    std::for_each(vec.begin(), vec.end(), func);

}
9
1
5
10
11
0
7
3
2
4
8

Iterate Through a Vector Using for_each with lambda

We can also use a lambda function to perform the std::cout operation for printing the elements in the vector.

#include <iostream>
#include <vector>

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Iterate through vector using for_each() with Lambda functoin

    std::for_each(vec.begin(), vec.end(), [](const auto & ele){

        std::cout<<ele<<"\n";

    });
}

In the above code, we applied a lambda function on each vector element to print each element.

9
1
5
10
11
0
7
3
2
4
8

Iterate Through a Vector in Reverse Order Using Indexing

We can iterate over a vector in reverse order from index N-1 to 0, where N is the size of the vector. Let’s look at an example with a vector of integers.

#include <iostream>
#include <vector>

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Length of vector

    unsigned int vec_size = vec.size();

    // Iterate over vector in reverse

    for(unsigned int i = vec_size-1; i>=0; i--){

        std::cout<<vec[i]<<"\n";

    }

    return 0;

}
8
4
2
3
7
0
11
10
5
1
9

Iterate Through a Vector in Reverse Order Using an Iterator

We can use a reverse iterator which traverses the vector in reverse. The vector class provides two functions which return a reverse iterator.

  • vector::rbegin: returns a reverse iterator that points to the reverse end.
  • vector::rend: returns a reverse iterator that points to the reverse beginning.

Let’s look at the use of reverse iterators to traverse a vector of integers with a while loop:

#include <iostream>
#include <vector>

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Vector iterator using auto keyword

    auto it = vec.rbegin();

    // Iterate over vector using while loop

    while(it != vec.rend())

        std::cout << *it << "\n";

        it++;

    }

    return 0;

}
8
4
2
3
7
0
11
10
5
1
9

Iterate Through a Vector in Reverse Order Using for_each with a Function

We can also use the for_each() function to iterate over all the elements between the start and end iterator and apply the callback function to each element. To iterate in reverse, we must pass the iterators returned by vector.rbegin() and vector.rend(). Let’s look at an example using a predefined callback function.

#include <iostream>
#include <vector>

// Callback function for for_each

void func(int const& value){

    std::cout<<value<<"\n";

}

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Iterate through vector using for_each() with Lambda functiin

    std::for_each(vec.rbegin(), vec.rend(), func);

}
8
4
2
3
7
0
11
10
5
1
9

Iterate Through a Vector in Reverse Order Using for_each with a lambda

We can also use a lambda function to perform the std::cout operation for printing the elements in the vector.

#include <iostream>
#include <vector>

int main() {

    // Vector of int

    std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8};

    // Iterate through vector using for_each() with Lambda function

    std::for_each(vec.rbegin(), vec.rend(), [](const auto & ele){

        std::cout<<ele<<"\n";

    });

}
8
4
2
3
7
0
11
10
5
1
9

Summary

Congratulations on reading to the end of this tutorial!

For further reading on C++, go to the articles:

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee