looping through vector c++ code example

Example 1: c++ iterate through vectgor

std::vector<int> vec_of_ints(100);
for (int i = 0; i < vec_of_ints.size(); i++){
 	std::cout << vec_of_ints.at(i) << " "; 
}
std::cout << std::endl;

Example 2: how to iterate trough a vector in c++

vector<int> myVector;

myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
myVector.push_back(4);

for(auto x: myVector){
	cout<< x << " ";

}

vector<pair<int,int>> myVectorOfPairs;

myVectorOfPairs.push_back({1,2});
myVectorOfPairs.push_back({3,4});
myVectorOfPairs.push_back({5,6});
myVectorOfPairs.push_back({7,8});

for(auto x: myVectorOfPairs){
	cout<< x.first << " " << x.second << endl;

}

Example 3: iterate over vector in c++

for (auto & element : vector) {
    element.doSomething ();
}

Example 4: c++ looping through a vector

for(std::vector<T>::size_type i = 0; i != v.size(); i++) {
    v[i].doSomething();
}

Example 5: iterate on vector c++

// vector::begin/end
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  for (int i=1; i<=5; i++) myvector.push_back(i);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Example 6: c++ looping through a vector

vector<int> vi;
...
for(int i : vi) 
  cout << "i = " << i << endl;

Tags:

Cpp Example