How to Iterate Through a Vector in C++

Jinku Hu Feb 12, 2024
  1. Vectors in C++
  2. Use the Traditional for Loop to Loop Through Vectors in C++
  3. Use the auto Keyword to Loop Through Vectors in C++
  4. Use the iterator Object to Loop Through Vectors in C++
  5. Conclusion
How to Iterate Through a Vector in C++

C++ provides a versatile container called a vector that allows for dynamic arrays with efficient memory management. When working with vectors, it’s essential to understand how to iterate over their elements, accessing and manipulating data as needed.

In this article, we will explore different methods for iterating through vector elements in C++.

Vectors in C++

Before delving into the methods of iterating over vector elements, let’s briefly discuss the significance of vectors in C++ and why they are widely used.

Vectors allow us to implement dynamic arrays in C++ with efficient and dynamic memory management and easy access to the elements of the array. Dynamic memory management indicates that the memory allotment is adjusted as elements are added and removed from the array.

Vectors provide several advantages, such as dynamic memory management and convenient member functions for common operations.

Remember to include the vector header file before using such structures. The vector header file has all the required definitions, which allow us to use such objects in the program.

Syntax to create a vector in C++:

std::vector<data - type> vector_name;
vector_name.push_back(element);

Here, std::vector declares the array of the required type. The push_back() function allows us to add elements to the array.

Let us now discuss the various methods available to loop through a vector in C++.

Use the Traditional for Loop to Loop Through Vectors in C++

A traditional for loop is basic in every programming language. To initiate a for loop in C++, we need to provide the starting value, the condition that needs to be checked in every iteration, and the increment that needs to be done in every iteration.

We can use the for loop to iterate through a vector in C++.

Syntax:

for (i = 0, i < vector.size(), ++i) {
  statements
}

We first declare an index with a value of 0. The loop will run till the time the index is less than the size of the vector, and we will increment it with a value of one to move to the next element in the next iteration.

Let us understand this better with a working example.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> delftstack = {45, 54, 87, 78};

  for (size_t i = 0; i < delftstack.size(); ++i) {
    std::cout << delftstack[i] << " ";
  }

  return 0;
}

In the above example, we create an integer vector called delftstack. We then initiate a variable i with a value of 0 and run the loop till the size of the array.

The size() function returns the same. The i variable is like an index value, and we use it to access the vector in every iteration.

Output:

Loop through vector in C++ using the for loop

As we can see in the output, we are able to loop through the vector delftstack and are able to display the contents stored inside the vector.

Use the auto Keyword to Loop Through Vectors in C++

This is a range-based method, only applicable to users working on C++ 11 and above.

The auto keyword in the for loop allows the compiler to automatically deduce the type of elements in the vector. We define a range in the loop, and it will execute for the same.

We can use this keyword along with the for loop to provide a more efficient way to loop through a vector.

Syntax:

for (const auto &element : vector_name) {
  statements;
}

We can understand the above syntax better with an example.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> delftstack = {45, 54, 87, 78};

  for (const auto &element : delftstack) {
    std::cout << element << " ";
  }

  return 0;
}

In the above example, we use the range-based method to loop through a vector.

The auto keyword deduces the type of vector and creates a reference, and we use the const keyword to ensure that the values are not changed. The value of the element is displayed in every iteration.

Output:

Loop through vector in C++ using the auto keyword

The output above displays the contents of the vector found after successfully running through all the iterations.

Use the iterator Object to Loop Through Vectors in C++

An iterator is an object that is used to loop through the elements of any data structure that supports iteration. It provides a reference to the data structure without exposing the underlying structure.

Syntax:

std::vector<int> vec_name std::vector<int>::iterator iterator_name =
    vec_name.begin();

The above syntax demonstrates how to create an iterator object that references a vector and initializes it with the first value of the vector.

We can use this method to loop through a vector. Take a look at the example below.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> delftstack = {45, 54, 87, 78};
  std::vector<int>::iterator i = delftstack.begin();
  for (i; i < delftstack.end(); i++) {
    std::cout << *i << " ";
  }

  return 0;
}

Here, we create an iterator i and assign it to the first element of the vector delftstack. The loop will execute till the vector is finished (i.end()), and we use the * pointer to access the value the iterator is pointing to.

Output:

Loop through vector in C++ using the iterator object

The output here displays the contents of the vector post looping through it, similar to the other methods mentioned above.

Conclusion

In this article, we have discussed several methods to loop through a vector in C++. It is very important to know how to loop through a vector because it allows us to access the elements individually and operate on them accordingly.

We discussed the use of the traditional for loop, which is the base for all the controls discussed in this article. It is a control flow statement that allows you to repeatedly execute a block of code for a specified number of iterations.

Another way to iterate through a vector in C++ is to use a range-based method for concise code. We used the auto keyword for automatic type inference during variable declaration. It allows the compiler to automatically deduce the data type of a variable based on its initializer.

In the last method, we used iterators, which allow the iteration through the elements of a container, such as an array, vector, list, or any other sequence-like structure. Iterators provide a way to traverse the elements of a container without exposing the underlying details of the container’s implementation.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ Vector