Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find pair by key within a vector of pairs

Tags:

c++

stl

vector

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.

like image 354
Daniel Del Core Avatar asked Mar 27 '14 01:03

Daniel Del Core


People also ask

How do you find a pair of a vector?

Declare a vector v. Declare key and value pair within v of the integer datatype. Call push_back() function to insert values in v vector. Call sort() function to sort all elements of the vector v.

How do you use a binary search in a vector pair?

We can search a pair in a sorted vector of pairs by using the built-in function “binary_search()”of STL library. We can search a first element of a pair in a sorted vector of pairs by using the built-in function “binary_search()”of the STL library.

How do you get the second element in pair?

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.


1 Answers

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 ); 
like image 134
BlackMamba Avatar answered Sep 19 '22 21:09

BlackMamba