Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List initialization of std::map with a struct as a key

I currently have this:

struct Foo {
    int value = 12;
    Foo(int a) : value(a) {}
};

and I am trying to do this:

std::map<Foo,int> m{
    {{1}, 2}
};   

Why is the above giving the compile error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error: invalid operands to binary expression ('const Foo' and 'const Foo')

>Solution :

When I compile the code you provided with g++, I get a different (and self-explanatory) error:

/usr/include/c++/12/bits/stl_function.h: In instantiation of ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Foo]’:
/usr/include/c++/12/bits/stl_function.h:408:20: error: no match for ‘operator<’ (operand types are ‘const Foo’ and ‘const Foo’)

Since you are using Foo as the key in a sorted container, you must tell the compiler how to compare one Foo to another.

For example, adding this method makes it compile:

bool operator<(const Foo& lhs, const Foo& rhs) {
  return lhs.value < rhs.value;
}

Or, if you are using C++20, you can simply add a defaulted three-way comparison to the struct to define all comparison operators:

friend auto operator<=>(const Foo&, const Foo&) = default;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading