Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
vector
array
communitycreator

How to iterate through a vector in C++

Sarah Tanveer

Vectors in C++

Vectors are a useful data structure in C++ that act like dynamic one-dimensional arrays.

There are several ways to iterate through a vector.

Syntax

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

Code

1. Use a for loop and reference pointer

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()
{
  //decleration 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;
}

Instead of []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.

2. 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()
{
  //decleration of int vector
  vector<int> vec = {1, 2, 3, 4, 5};
  int vecSize = vec.size(); // returns length of vector

  //decleration 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;
}

3. Use the auto keyword

The 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() {
  //decleration 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;
}

RELATED TAGS

c++
vector
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring