I am currently working on a homework assignment. A question asks....
"Can a map be declared with int as the key data type (i.e. map<int, sometype>m)? Can a map be declared with a char as the key data type? Why or why not?"
I cannot for the life of me find a definitive answer to this question, either in my book or online. Any help would be greatly appreciated. Thanks in advance.
Yes.
Yes.
Why not? Only requirements on keys is that they should be destructible and if you do not provide custom comparator, they should have operator< providing strict weak ordering.
Other things like existence of a copy or parametrised constructors only changes how map can be used.
#include <iostream>
#include <map>
#include <cmath>
class Point
{
public:
Point(int x_, int y_) : x(x_), y(y_) {}
private:
int x;
int y;
friendclass point_order;
};
//We do not use operator< because there is no sensible implementation for points
class point_order //custom function object class
{
public:
booloperator()(const Point& lhs, const Point& rhs) const
{
//Orders by distance from center
return std::hypot(lhs.x, lhs.y) < std::hypot(rhs.x, rhs.y);
}
};
int main()
{
std::map<Point, int, point_order> foo; //map using custom comparator
Point x(1, 1);
Point y(2, 3); //farther from center than x
foo[x] = 10;
foo[y] = 20; //Would be shown second
foo[{1, 1}] = 30; //Overwriting value of 10
for(auto i: foo)
std::cout << i.second << '\n';
}