Should I iterate over a vector by iterator or access operator?

I have a vector declared as

std::vector<int> MyVector;
MyVector.push_back(5);
MyVector.push_back(6);
MyVector.push_back(7);

How do I use it in a for loop?

Iterating it with an iterator?

for (std::vector<int>::iterator it=MyVector.begin(); it!=MyVector.end(); ++it)
{
    std::cout << "Vector element (*it): " << *it << std::endl;
}

Or its access iterator?

for (std::vector<int>::size_type i=0; i<MyVector.size(); i++)
{
    std::cout << "Vector element  (i) : " << MyVector.at(i) << std::endl;
}

In the examples I found on the Internet, both of them are used. Is one of them superior to the others under any conditions? If not, when should I prefer one of them over the other?

+5
source share
4 answers

- , . , unimpacted.It , , .

std::vector::at() , . , . , operator[].
, , , .

+5

std::vector [] operator, , , std::vector::at() for ( for std::vector:: at()).

, , .

++ 11, , .

+3

, ++ 11, :

for (auto i : MyVector)
{
    std::cout << i;
}

BOOST_FOREACH ++ 03:

BOOST_FOREACH(int& i, MyVector)
{
  std::cout << i;
}

std::copy:

std::copy(MyVector.begin(),
          MyVector.end(), 
          std::ostream_iterator<int>(std::cout, "\n"));

, at() , , . , , . , , . :

for (std::vector<int>::iterator it=MyVector.begin(), end = MyVector.end(); it!= end; ++it)
{
    std::cout << "Vector element (*it): " << *it << std::endl;
}

end end() . , , .

+2

" " ( , at()at() , -, , ). , , . ++ - , , (, ) .

:

  • . , .

  • . vector , , , vector. ( , , , .)

  • , , - , , , . ( , , int, size_t .)

+1
source

All Articles