C++ 在对的向量中按键查找对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22676301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:09:30  来源:igfitidea点击:

Find pair by key within a vector of pairs

c++vectorstl

提问by Daniel Del Core

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.

我想在成对的向量上调用 find 函数。在调用 find 函数时,我只有要搜索的键。

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.

我的理解是我需要将一个函数作为参数传递给 find 来为我做比较,但我找不到合适的例子。

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 valueafter 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 findValis the fuzzy area for me. I'd also be open to better ways of implementing the logic.

上的实现对findVal我来说是模糊区域。我也愿意接受更好的实现逻辑的方法。

回答by BlackMamba

you don't need use find, please use find_if, this is the link:http://www.cplusplus.com/reference/algorithm/find_if/

你不需要使用find,请使用find_if,这是链接: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:

如果您在 C++11 之前使用 C++ 标准,以后,您将需要一个函数而不是 lambda:

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