I have a std::multimap<int, X*> where X is a user-defined type. I want to find a specific key-value-pair within this multimap (i.e. an iterator pointing to this pair).
(A) Complete Example:
#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):
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.
(B) Using std::find_if with a lamdba function with const int, the code compiles:
auto it = std::find_if(myMap.begin(), myMap.end(), [myX](std::pair<const int, X*>& node){ return 5 == node.first && (&myX) == node.second; } );
Questions:
- Why is the type of the keys in the multimap
const intand notint? - 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 (as described by Igor Tandetnik in the comments)?
Because the Key in all standard maps is immutable.
Here's a simplified example that doesn't use
X*butXin the map:Demo
If many Values may be found, just put the
find_ifin a loop:Demo