C ++ sets search for an element of a pair?

So i have a set pairs<string ,string>

And I want to use find()to search for one line that would be in the "first" of the pair, then if I first find this line, I want to return the second of this function.

My current attempt ...

myList::iterator i;

i = theList.find(make_pair(realName, "*"));

return i->second;
+5
source share
3 answers

Is C ++ 11 acceptable?

auto it = find_if(theList.begin(), theList.end(),
    [&](const pair<string, string>& val) -> bool {
        return val.first == realName;
    });

return it->second;

Or in C ++ 03, first define a functor:

struct MatchFirst
{
        MatchFirst(const string& realName) : realName(realName) {}

        bool operator()(const pair<string, string>& val) {
                return val.first == realName;
        }

        const string& realName;
};

then name it like this:

myList::iterator it = find_if(a.begin(), a.end(), MatchFirst(realName));
return it->second;

This will return only the first match, but from your question, it looks like everything you expect.

+6
source

std::set<std::pair<std::string, std::string> > , , . , , std::map<std::string, std::string>.

+2

< std::pair , "" - . , :

 typedef std::pair<std::string, std::string> StringPair;
 typedef std::set<StringPair> Set;

 std::string const* find_first(Set const& s, std::string const& key) {
   Set::const_iterator const it = s.lower_bound(std::make_pair(key, ""));

   // Check that it actually points to a valid element whose key is of interest.
   if (it == s.end() or it->first != key) { return 0; }

   // Yata!
   return &it->second;
 }

lower_bound .

, , value.

  • end(), .
  • it->first >= key, > ( )

, . , :

typedef std::pair<Set::const_iterator, Set::const_iterator> SetItPair;

SetItPair equal_range_first(Set const& s, std::string const& key) {
  StringPair const p = std::make_pair(key, "");
  return std::make_pair(s.lower_bound(p), s.upper_bound(p));
}

s, key. :

for (Set::const_iterator it = range.first; it != range.second; ++it) {
  // do something
}

, lower_bound upper_bound .

  • lower_bound end(), upper_bound,
  • lower_bound node, it->first > key, upper_bound node,

: , , , ... .

+1

All Articles