867 Subj : Re: BC5.02 STL question To : borland.public.cpp.borlandcpp From : Ed Mulroy [TeamB] Date : Mon May 31 2004 12:22 pm I think you have a trivial advantage from using an iterator. However there is something in your code which makes it slower than it could be: > int i; > for (i = 0; i < stuff.size(); i++) > { > --- do something with stuff[i] --- > } You are calling size() in every iteration of the loop. Instead do this: ------------------ int i, n; for (i = 0, n = stuff.size(); i < n; ++i) { --- do something with stuff[i] --- } vector::iterator i = stuff.begin(); vector::iterator ender = stuff.end(); while (i != ender) { --- do something with *i --- ++i; } ------------------ These loads stuff.size() or stuff.end() only once. They also changes the post-increment to pre-increment. You are not using the value prior to incrementing and that is most inefficient. For an int the compiler knows about how people do this so optimizes it to ++i but if i were an iterator or other class item it is inefficient. If you use the index and don't care about the order (front to back vs back to front) you can also do this for a (possibly trivial) gain: ------------------ int i; for (i = stuff.size(); i--; ) { --- do something with stuff[i] --- } ------------------ and if you don't need 'i' later ------------------ for (int i = stuff.size(); i--; ) { --- do something with stuff[i] --- } ------------------ .. Ed > MarvinAvery wrote in message > news:40bb312a$1@newsgroups.borland.com... > > I have an STL question and since I am using BC5.02, I > thought I'd ask it here. > > I have a vector: > vector stuff; > > I wish to traverse the vector. Which is better-- use an > index: > > int i; > for (i = 0; i < stuff.size(); i++) > { > --- do something with stuff[i] --- > } > > Or use an iterator: > > vector::iterator i = stuff.begin(); > while (i != stuff.end()) > { > --- do something with *i --- > i++; > } > > Or does it matter? . 0