I have a vector declared as
std::vector<int> MyVector; MyVector.push_back(5); MyVector.push_back(6); MyVector.push_back(7); How do should I use it in a for loop?
By 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 by 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 examples I found on internet both of them are used. Is one of them superior to the other under all conditions? If not, when should I prefer one of them over the other?
std::vector::atdoes and why you use it in your code. If usingstd::vector::atinstead ofstd::vector::operator[], iterators will most probably always be faster (disregarding any other advantages).