Maps Question

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.
thank you, can I use a custom class as the key data type then? ex. <Point, string>?
Yes if you can provide meaningful operator < or custom comparator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <map>
#include <cmath>

class Point
{
public:
    Point(int x_, int y_) : x(x_), y(y_) {}
private:
    int x;
    int y;
    friend class point_order;
};

//We do not use operator< because there is no sensible implementation for points

class point_order //custom function object class
{
public:
    bool operator()(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';
}
30
20
Last edited on
Registered users can post here. Sign in or register to post.