Daniel D C Daniel D C - 11 months ago 138
C++ Question

Find pair by key within a vector of pairs

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 cant 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
//Item does not exist
//Not found, insert in map
sortList.push_back( pair<string,int>(Users.userName, 1) );

//Sort the list


The implementation on "findVal" is the fuzzy area for me. I'd also be open to better ways of implementing the logic.

Answer Source

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(),
    [](const std::pair<std::string, int>& element){ return element.first == User.name;} );

If you are not using C++11, please use this code:

bool isEqual(const std::pair<std::string, int>& element)
    return element.first ==  User.name;
it = std::find_if( sortList.begin(), sortList.end(), isEqual );