在多地图中搜索价值

Chr*_*isD 2 c++ multimap c++11

假设我有以下内容:

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); 
}
Run Code Online (Sandbox Code Playgroud)

检查third_foowith 密钥"A"是否已经在我的multimap.

pha*_*tom 5

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
Run Code Online (Sandbox Code Playgroud)

为此,您必须添加operator ==toFoo或使用带有std::find_if. 这会将您的呼叫更改为如下所示:

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