Reputation: 3221
I want to call the find function on a vector of pairs. At the time the find function is called I only have the key to search by.
My understanding is that I need to pass a function into find as an argument to do the comparison for me but I can't find a proper example.
The reason I'm sorting the pairs within a vector opposed to a map container is because I want to be able to sort the pairs by value after the population process.
vector< pair<string, int> > sortList;
vector< pair<string, int> >::iterator it;
for(int i=0; i < Users.size(); i++)
{
it = find( sortList.begin(), sortList.end(), findVal(Users.userName) );
//Item exists in map
if( it != sortList.end())
{
//increment key in map
it->second++;
}
//Item does not exist
else
{
//Not found, insert in map
sortList.push_back( pair<string,int>(Users.userName, 1) );
}
}
//Sort the list
//Output
The implementation on findVal
is the fuzzy area for me. I'd also be open to better ways of implementing the logic.
Upvotes: 40
Views: 111142
Reputation: 60218
From C++20, you can use ranges to write:
auto it = std::ranges::find(sortList, Users.userName,
&std::pair<std::string, int>::first);
which is much easier to read. The 3rd argument is a projection, i.e. it says to look only at the first
member of every pair
in the vector, when comparing it against the second argument.
Upvotes: 11
Reputation: 10254
you don't need use find
, please use find_if
, this is the link:http://www.cplusplus.com/reference/algorithm/find_if/
auto it = std::find_if( sortList.begin(), sortList.end(),
[&User](const std::pair<std::string, int>& element){ return element.first == User.name;} );
If you are using C++ standard before C++11, later, you'll need a function instead of a lambda:
bool isEqual(const std::pair<std::string, int>& element)
{
return element.first == User.name;
}
it = std::find_if( sortList.begin(), sortList.end(), isEqual );
Upvotes: 63