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.
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.
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.
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.
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 );
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