Reputation: 1665
I am improving my C++ skills by learning to use better the algorithms in the standard library. I have an issue that I am not sure how to solve correctly using algorirhtms. I need to check if an element exists in a vector and if it exists, get its index.
With a raw loop I would use an integer and increment it for each iteration.
With algorithms I have only been able to use std::find
and then use std::distance
, but this requires more computations than a raw loop. What would be the best way to do this task using algorithms?
Upvotes: 0
Views: 443
Reputation: 238311
What would be the best way to do this task using algorithms?
Use std::find
and then use std::distance
.
Except for containers which have a more efficient find
member function such as associative containers. In that case, use find
member function and std::distance
.
There are also data structures with more efficient ways to calculate the distance than can be achieved through iterators, but no standard container use such data structure.
but this requires more computations than a raw loop.
It does not (assuming an optimising compiler).
why not?
Because the standard algorithms in question don't need to do anything that the raw loop doesn't do.
Upvotes: 2