[英]Finding a key-value-pair within a std::multimap with key of type int
I have a std::multimap<int, X*>
where X
is a user-defined type.我有一个
std::multimap<int, X*>
,其中X
是用户定义的类型。 I want to find a specific key-value-pair within this multimap (ie an iterator pointing to this pair).我想在此多重映射中找到特定的键值对(即指向此对的迭代器)。
(A) Complete Example: (A) 完整示例:
#include <map>
#include <algorithm>
class X {};
int main()
{
X myX;
std::multimap<int, X*> myMap;
auto it = std::find(myMap.begin(), myMap.end(), std::make_pair(5, &myX));
return 0;
}
However, this does not compile (gcc 12.2.1 with -std=gnu++2a
):但是,这不会编译(带有
-std=gnu++2a
的 gcc 12.2.1):
no match for ‘operator==’ (operand types are ‘std::pair<const int, X*>’ and ‘const std::pair<int, X*>’)
So it seems to me somehow int
gets converted to const int
.所以在我看来
int
以某种方式转换为const int
。
(B) Using std::find_if
with a lamdba function with const int
, the code compiles: (B) 使用带有
const int
的 lamdba function 的std::find_if
,代码编译:
auto it = std::find_if(myMap.begin(), myMap.end(), [myX](std::pair<const int, X*>& node){ return 5 == node.first && (&myX) == node.second; } );
Questions:问题:
const int
and not int
?const int
而不是int
?Why is the type of the keys in the multimap const int and not int?
为什么 multimap 中键的类型是 const int 而不是 int?
Because the Key in all standard maps is immutable.因为所有标准映射中的Key都是不可变的。
How to fix it in a more natural way than using a (complex) lambda function like in (B) or by first looking up by key and then searching within its values?
如何以比在 (B) 中使用(复杂的)lambda function 或首先按键查找然后在其值内搜索更自然的方式修复它?
Here's a simplified example that doesn't use X*
but X
in the map:这是一个不使用
X
X*
而是在 map 中使用 X 的简化示例:
#include <algorithm>
#include <iostream>
#include <map>
struct X {
bool operator==(const X& rhs) const { return m_value == rhs.m_value; }
int m_value;
};
int main() {
std::multimap<int, X> myMap{
{4, {1}}, {5, {2}}, {6, {3}}, {4, {4}}, {5, {5}}, {6, {6}}
};
// get the range of _Key_s equal to 5
auto [first, last] = myMap.equal_range(5);
// the lambda - here used to find the first entry with the _Value_ `X{2}`
auto cond = [](auto&& pair) { return pair.second == X{2}; };
if (auto it = std::find_if(first, last, cond); it != last)
{
auto& [k, v] = *it;
std::cout << k << ' ' << v.m_value << '\n';
}
}
If many Values may be found, just put the find_if
in a loop:如果可以找到很多值,只需将
find_if
放入循环中:
for(;(first = std::find_if(first, last, cond)) != last; ++first) {
auto& [k, v] = *first;
std::cout << k << ' ' << v.m_value << '\n';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.