【问题标题】:Find pair by key within a vector of pairs在对的向量中按关键字查找对
【发布时间】:2014-03-27 01:03:15
【问题描述】:

我想在成对的向量上调用 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 上的实现对我来说是一个模糊的区域。我也愿意接受更好的实现逻辑的方法。

【问题讨论】:

    标签: c++ vector stl


    【解决方案1】:

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

    【讨论】:

    • @DanielDC 你的系统设置为 C++11 吗?
    • 不确定,如何查看
    • 试试g++ --versionclang++ --versioncompilerExeName --version
    • @DanielDC 是的,现在我知道 c++11 支持是非常可能的。你用的是 Xcode 还是别的?
    • 我也可以将 User.name 作为参数传递给这个新函数吗??
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 2013-07-10
      • 2010-11-27
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多