Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++ - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...