Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ set search for pair element?

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;
like image 570
user1288735 Avatar asked Mar 23 '12 16:03

user1288735


People also ask

How do you find an element in a pair of pairs?

To access the elements of the pair, use variable name followed by dot operator followed by the keyword 'first' or 'second', these are public members of class pair.

How do you get the first element in pair?

To access the elements, we use variable name followed by dot operator followed by the keyword first or second.

Can we insert pair in set?

No duplicate pair is allowed in a set of pairs. Elements of such a set, i.e pairs are sorted according to the key that is the first element of each pair present in the set. We can search for a particular pair, add pair, remove pair and can get the count of pair present.

How do you find the third element of a set?

Now, to access an element at nth index we need to create an iterator pointing to starting position and keep on increment the iterator till nth element is reached i.e. std::cout<<"3rd Element in set = "<<*setIt<<std::endl; std::set<std::string>::iterator setIt = setOfStr.


2 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 call it like so:

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

This will only return the first match, but from your question, it looks like that's all you're expecting.

like image 89
Rick Yorgason Avatar answered Oct 07 '22 20:10

Rick Yorgason


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 a std::map<std::string, std::string> instead.

like image 35
Dietmar Kühl Avatar answered Oct 07 '22 20:10

Dietmar Kühl