custom key value for associative container

Hello forum,

I would like to have a customized key value in the multimap container. The type is as follows:


1
2
3
4
struct HilbertCoordinate
{
    short int x,y;
}


In that case how the key values along with the mapped values will be sorted in the multimap. Some hints are earnestly requested.


Thanks
The third argument to the std::multimap constructor is a comparison function.
Simply provide your own comparison function that compares two HilbertCoordinate objects.
http://www.cplusplus.com/reference/map/multimap/

Compare
A binary predicate that takes two element keys as arguments and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are element keys, shall return true if a is considered to go before b in the strict weak ordering the function defines.
The multimap object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)).
This can be a function pointer or a function object (see constructor for an example). This defaults to less<T>, which returns the same as applying the less-than operator (a<b).
Aliased as member type multimap::key_compare.

Hi

I have the class defined as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class HilbertCoordinates
{
public:

    HilbertCoordinates(short int x_, short int y_)
        : x(x_),y(y_)
    {

    }

    short int x;
    short int y;

    bool operator() (const HilbertCoordinates &lhs, const HilbertCoordinates &rhs)
    {
        return ((lhs.x <= rhs.x) && (lhs.y <= rhs.y));
    }
};


Then inside the main function I have a multimap declared as follows:

1
2
3
4
5
6
7
8
9
10

int main()
{
    std::multimap<HilbertCoordinates,int> table;

    table.insert(std::pair<HilbertCoordinates,int>(HilbertCoordinates(70,10),2));

    return 0;
}



I hoped that the value will be inserted into the map sorted in the ascending order, instead I am getting error.
Topic archived. No new replies allowed.