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;
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.
To access the elements, we use variable name followed by dot operator followed by the keyword first or second.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With