vector loop?

does anyone know the best way to go about starting a loop to search for values in a vector? for example my vector contains 10 values ranging from 1-11, which is the best way to search for these values in a loop?
I'd use an iterator as the index in a for loop to step through the vector. Assuming your vector contains ints:

1
2
3
4
5
	vector<int>::iterator iter;
	for (iter = myVector.begin(); iter! = myVector.end(); iter++)
        {
                 // do your thing
        }
Last edited on
I don't know that there really is another decent way than using an iterator, to be honest. Just compare the value of the iterator to the value you're looking for and page through the list like in the example above.
Note that it is good practice to favour the pre-increment form of the increment operator (it very prob makes no difference in this case, after optimization, but it can in others situations. So it's a good habit to develop).

You should also avoid calling end() repeatedly, if the size of the vector is constant (i.e. no insertions or deletions). So I would code this as:

1
2
3
4
5
    const vector<int>::iterator iterEnd = myVector.end();
    for (vector<int>::iterator iter = myVector.begin(); iter! = iterEnd; ++iter)
    {
        // do your thing
    }


In some implementations accessing by index can be faster. This is unlikely to be true for the release versions of modern implementations of STL, but if you've enabled checked/debug iterators in your code, it will have an effect.

Note that the actual best approach would be algorithm based: find or find_if, if you're searching; for_each, transform, ... if you're processing all elements.

Andy
Topic archived. No new replies allowed.