I have a collection of elements that I need to operate over, calling member functions on the collection:
std::vector v;
... // vector is popula
std::vector v, matches;
std::vector::iterator i = v.begin();
MyPred my_pred;
while(true) {
i = std::find_if(i, v.end(), my_pred);
if (i == v.end())
break;
matches.push_back(*i);
}
For the record, while I have seen an implementation where calling end()
on a list
was O(n), I haven't seen any STL implementations where calling end()
on a vector
was anything other than O(1) -- mainly because vector
s are guaranteed to have random-access iterators.
Even so, if you are worried about an inefficient end()
, you can use this code:
std::vector v, matches;
std::vector::iterator i = v.begin(), end = v.end();
MyPred my_pred;
while(true) {
i = std::find_if(i, v.end(), my_pred);
if (i == end)
break;
matches.push_back(*i);
}