So I have a set of pairs<string ,string>
And I want to use find()
to search for a single string which would be in the "first" of the pair, then if I find that string in first I want to return second from that function.
My current attempt is..
myList::iterator i;
i = theList.find(make_pair(realName, "*"));
return i->second;
You can use
std::set<std::pair<std::string, std::string> >
for this but you will need a custom comparison object for this because the pair's relational operator takes both elements for this. That said, it seems as if you actually should use astd::map<std::string, std::string>
instead.Is C++11 acceptable?
Or in C++03, first define a functor:
then call it like so:
This will only return the first match, but from your question, it looks like that's all you're expecting.
The definition of
<
forstd::pair
implements a lexicographical order and""
is the minimum element for strings. Combining this we get:The trick is using
lower_bound
appropriately.end()
, then it did not find anything interesting.it->first >= key
so we get rid of the>
case (of no interest to us)I would point out though that this only returns the first element of the range. If you are interested in all elements, try:
This will return the full range of nodes in
s
whose first element is equal tokey
. You then just have to iterate over this range:And you don't even have to worry whether the return of
lower_bound
orupper_bound
was end or not.lower_bound
returnsend()
, then so doesupper_bound
, and the loop is skippedlower_bound
points to a node for whichit->first > key
, thenupper_bound
will point to that same node, and the loop is skippedThat is the power of ranges: no need to make special checks, the ranges just end up empty when there is no match, and so the loop over them... is skipped in a single check.