C++ vector for loop code example

Example 1: c++ iterate over vector

for(auto const& value: a) {
     /* std::cout << value; ... */
}

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: for loop vector

for (auto i = v.begin(); i != v.end(); i++)
    {
        std::cout << *i << endl;
    }

Example 4: c++ looping through a vector

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

Example 5: for vector c++

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

Example 6: for vector c++

for (auto it = begin (vector); it != end (vector); ++it) {
    it->doSomething ();
}

Tags:

Cpp Example