I picked up on the STL containers fairly quickly after starting to learn C++, one thing I've never really understood the purpose of is iterators. Until very recently, when looping through the elements in a vector, I would use something like this:
1 2 3 4
|
for(unsigned int i=0; i<vectorName.size(); i++)
{
vectorName.at(i).something();
}
|
A short while ago I downloaded a simple high-res timer, so I can work on optimizing a rogue-like game I'm writing, and figured a good way to test the library would be to compare the speed of looping through a vector with an iterator, rather than the integer method I've been using. The results rather surprised me...
Testing vector.at(#) method...
100,000 integers in 0.0109804 seconds.
Testing iterator method...
100,000 integers in 0.248681 seconds.
Press any key to continue . . . |
It seems to take anywhere from 10-20 times as long to loop through it with iterators.... If not for the speed, and seemingly not for the easy of use (at least, as a newbie, the other method seemed simpler), why use iterators at all?
So long as the operations performed on the objects in the vector are the same, the time ratio stays about the same. If I use .at() for every operation to the object it starts to slow down a little bit, but that can be avoided by creating a pointer to the object, and performing operations through that.
Thank you for your time,
Timothy
[EDIT]: If this belongs in the "General C++ Programming" section, could a moderator please move it? Wasn't sure which section to put it in, and a "Beginner" section is usually the safer bet.