c++ - 在多 map 中搜索值

标签 c++ c++11 multimap

假设我有以下内容:

class Foo {
public:
    Foo(int x) {
        _x = x;
    }
    int _x;    
}

int main() {
    multimap<string, Foo> mm;
    Foo first_foo(5);
    Foo second_foo(10);

    mm.insert(pair<string, Foo>("A", first_foo));
    mm.insert(pair<string, Foo>("A", second_foo));

    Foo third_foo(10); 
}

检查 third_foo"A" 是否已经在我的 multimap 中的好方法是什么?

最佳答案

std::find可用于在任何可迭代的容器中查找对象。

在你的代码中它看起来像这样:

auto it = std::find(mm.begin(), mm.end(), std::pair<string, Foo>("A", third_foo));

if (it == mm.end())
    // third_foo is not in the multimap
else
    // third_foo is in the multimap

为此,您必须向 Foo 添加一个 operator == 或使用带有 std::find_if 的谓词。这会将您的调用更改为如下所示:

auto it = std::find_if(mm.begin(), mm.end(), 
    [&third_foo](auto v)
    { 
        return v.second._x == third_foo._x;
    });

关于c++ - 在多 map 中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758235/

相关文章:

c++ - 在 C++11 中替换元组中的类型

java - 获取 MultiMap 中的 EntrySet

java - 更快的集合交集方法

C++:如何声明私有(private)成员对象

关于比较器的 C++ 模板问题

c++ - 指针加法

javascript - Qml 属性钩子(Hook)

c++ - 执行数千次比较的最快方法

C++ va_list 函数重载

java - 如何将来自父 Map 的 Map 值与 java 8 流结合起来