在成对的向量中按键查找成对 [英] Find pair by key within a vector of pairs

查看:28
本文介绍了在成对的向量中按键查找成对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对成对的向量调用 find 函数.在调用 find 函数时,我只有搜索的关键字.

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 来为我做比较,但我找不到合适的例子.

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 

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

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

推荐答案

你不需要使用find,请使用find_if,这是链接:http://www.cplusplus.com/reference/algorithm/find_if/

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

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

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

这篇关于在成对的向量中按键查找成对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆