for loop c++ elements in vector code example

Example 1: c++ iterate over vector

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

Example 2: for loop vector

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

Example 3: 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;
}

Tags:

Cpp Example