假设我有以下内容:
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/