Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I iterate a vector by iterator or by 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 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?

like image 371
hkBattousai Avatar asked Sep 24 '12 07:09

hkBattousai


1 Answers

The first format is more generic format for iterating over standard library containers so it is more common and intuitive. If you need to change your container then this iterating code remains unimpacted.It will work for every standard library container type, thus it gives you more generic code.

In second format, std::vector::at() checks for the bounds each time it gets called on every iteration, so it may be a little detrimental to performance. This overhead is not present in the first format as there is no bounds checking involved.Note that same is the case with using operator[].
Note the performance lag though is not as much as you will notice it unless you are operating on a huge data.

like image 126
Alok Save Avatar answered Oct 14 '22 03:10

Alok Save