Find pair by key within a vector of pairs(在成对的向量中按键查找成对)
问题描述
我想对成对的向量调用 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 );
                        这篇关于在成对的向量中按键查找成对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在成对的向量中按键查找成对
				
        
 
            
        - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 - 从python回调到c++的选项 2022-11-16
 - Stroustrup 的 Simple_window.h 2022-01-01
 - 使用/clr 时出现 LNK2022 错误 2022-01-01
 - 近似搜索的工作原理 2021-01-01
 - STL 中有 dereference_iterator 吗? 2022-01-01
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 - C++ 协变模板 2021-01-01
 - 静态初始化顺序失败 2022-01-01
 
						
						
						
						
						
				
				
				
				