Do you mean cout << mymap[make_pair(1,2)] << endl; ? (1,2) is non-sensical, at least in this context. You must have an std::pair to be used as your key, and that means following what @andre just commented. Yes!
We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type. Now, we will create a data structure that defines a new data type. And use it as a key for the map.
The C++ function std::map::find() finds an element associated with key k. If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end().
map is often implemented using red-black trees, while unordered_map is often implemented using hash tables.
Try and make operator <
const
:
bool operator<(const coord &o) const {
(Your = operator
should probably be == operator
and const
as well)
By far the simplest is to define a global "less than" operator for your struct in stead of as a member function.
std::map uses - by default - the 'lessthan' functor which, in turn, uses the global "operator<" defined for the key type of the map.
bool operator<(const coord& l, const coord& r) {
return (l.x<r.x || (l.x==r.x && l.y<r.y));
}
As mentioned in the answer by Andrii, you can provide a custom comparison object to the map
instead of defining operator<
for your struct. Since C++11, you can also use a lambda expression instead of defining a comparison object. Moreover, you don't need to define operator==
for your struct to make the map
work. As a result, you can keep your struct as short as this:
struct coord {
int x, y;
};
And the rest of your code could be written as follows:
auto comp = [](const coord& c1, const coord& c2){
return c1.x < c2.x || (c1.x == c2.x && c1.y < c2.y);
};
std::map<coord, int, decltype(comp)> m(comp);
Code on Ideone
Another solution, which may be used for third-party data types, is to pass a Comparison object
as third template parameter.
example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With