1

I have a pair: typdef pair <unsigned char *, vector<int>> pair_t

I need to implement my own comparison function for that map, so I tried :

struct myCmp
{
   int operator()(unsigned char arr_1[10], unsigned char arr_2[10])
   {
    return memcmp(arr_1, arr_2, 10);
   }
};

typdef pair <unsigned char *, vector<int>, **myCmp**> pair_t;
pair_t data(someCharArr, someIntVector);

The error message I get is:

wrong number of template argument (3 should be 2)

I did the same thing with map and it was fine.

How can create my own compare function for pair?

How can I be sure that the pair_t data(someCharArr, someIntVector); will find the correct key (in case of char * as key)?

Thanks.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
user1673206
  • 1,671
  • 1
  • 23
  • 43
  • 2
    Why not use a `std::sting` instead of a `char *`. If you use a `std::string` the built in comparison operator should work. – NathanOliver Dec 09 '15 at 17:40
  • `std::pair` does not take a comparison operator. They are already defined in terms of the pair's components. – Anon Mail Dec 09 '15 at 17:42
  • I cant use string because all the data I get is char *, and I can't be sure that the the char * will not contain any '0' that will interrupt the comparison of strings- if I will convert the char * to string – user1673206 Dec 09 '15 at 18:39
  • In this case, how about using a `std::vector`? You can compare vectors for equality, less than and greater than (it compares its elements lexicographically, like a string does) and won't care about having `'\0'` in the middle. – SirGuy Dec 09 '15 at 21:23

2 Answers2

2

You seem to be confused about responsibilities of different classes. It's not the std::pair that needs to worry about how to compare pairs together, it's the std::map who needs to worry about how to sort its keys.

    typedef std::map<unsigned char*, std::vector<int>, myCmp> map_t;

From how you implement the comparison function and your comment on why you can't use strings, I actually recommend using a std::array instead of a unsigned char *. Your code then looks more like:

    typedef std::map<std::array<unsigned char, 10>, std::vector<int> > map_t;

This works because std::array implements all the comparison operators allowing you to use them as keys in a map.

This is going off of the fact that you seem to know the length of your array at compile time, and that it is always 10. If you don't actually know the length of your arrays at compile time, then you would use a std::vector<unsigned char> instead of the std::array.

SirGuy
  • 10,660
  • 2
  • 36
  • 66
1

std::pair is just a struct with two members, It have no comparison object built in.

You may be confused for a comparison object given for std::map (which in its turn, holds sequence of std::pair).

David Haim
  • 25,446
  • 3
  • 44
  • 78