在对矢量中按键查找对

时间:2014-03-27 01:03:15

标签: c++ vector stl

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

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

我在对应于地图容器的向量内对对进行排序的原因是因为我希望能够在填充过程之后按值对对进行排序

    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上的实施对我来说是模糊的区域。我也愿意接受更好的方法来实现逻辑。

2 个答案:

答案 0 :(得分:30)

您不需要使用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;} );

如果您在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 );

答案 1 :(得分:1)

从 C++20 开始,您可以使用 ranges 来编写:

auto it = std::ranges::find(sortList, Users.userName, 
                            &std::pair<std::string, int>::first);

这更容易阅读。第三个参数是一个投影,即它说在将它与第二个参数进行比较时只查看向量中每个 firstpair 成员。