On May 15, 4:07 pm, techie <jignati...@googlemail.comwrote:
I want to find an element in a sequence or map by comparing its value
(not the key). I can search for an element with a particular value in
a sequence or map by iterating through the elements one by one using
an iterator for the container. I could alternatively use the the
std::find or std::find_if algorithms to find an element in a sequence
or map respectively. For example, to find an element in a map I could
write a function object to check the value of an element:http://www.josuttis.com/libbook/cont/mapfind.cpp.html
I guess internally the std::find or std::find_if internally use
iterators to search for an element. Is there any advantage of using
the algorithms over for loops that use iterators. What is the best
most efficient method? Using algorithms or using iterators?
There is no real difference in efficiency. In both cases, you
are doing a linear search. The advantage of find or find_if is
that the name of the function says this immediately, up front.
The disadvantage is that if you don't already have a
predicate handy for the job, you have to write one---if the
logic of the predicate is connected to the logic of the calling
function, this means separating the logic into two separate
places, since the predicate cannot be a local class. (Normally,
this will very rarely be the case, unless you write functions
which are too complex to begin with. But it's still not always
the most readable solution to replace a three token in the loop
predicate with a full class definition outside of the function.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34