dbrettschneider
dbrettschneider

Reputation: 3183

C++ map insert with custom key fails

I have a custom class as a key in a map. When I try to insert an item into the map, the program terminates. There has to be a problem with the creation of the key.

class MyKey {
    char* data;
    bool operator<(const MyKey& s) const {
        for(int i = 0; i < (int)(sizeof(data)/sizeof(char)); i++) {
            if(data[i] > s.data[i])
            return false;
        }
        return true;
    }
}

map<MyKey, char>* map = new map<MyKey, char>;
MyKey* key = new MyKey(...);
map->insert(make_pair(*key, '0'));

The program terminates at the insert.

Upvotes: 0

Views: 1573

Answers (3)

Shawnone
Shawnone

Reputation: 860

From your example code, the operator < would not be called because you only insert one element in the map. And you said you don't implement a copy constructor. So following code would be a problem:

class MyKey {
public:
    MyKey()
    {
        data = new char[10];
    }
    ~MyKey()
    {
        delete data;
    }

private:
    char* data;
};

Upvotes: 0

Sanish
Sanish

Reputation: 1719

The following works and prints A.

    #include <iostream>
    #include <map>
    using namespace std;

    class Key
    {
    public:
         Key(int x):data(x) {}
         bool operator<(const Key &k) const { return(data < k.data); }
    private:
         int data;
    };

   int main()
   {
        Key myKey(10);
        map<Key, char> m;
        m.insert(make_pair(myKey, 'A'));
        map<Key, char>::iterator it = m.find(myKey);
        if (it != m.end())
        {
            cout << (*it).second << endl;
        }
   }

Upvotes: 0

Jason
Jason

Reputation: 32510

You can't determine the size of an array from the pointer alone like you're attempting to-do in the for-loop of your operator< function ... You will have to, at some point, pass in the size of the array that is being pointed to by data so that you don't overflow the bounds of the array data is pointing to. Since data is a pointer, sizeof(data) simply returns the size of a pointer on your platform, not the size of the array being pointed to by data.

For C++, rather than using an allocated array, you should possibily use a STL container that you can directly query for the size of the container object ... this could include std::string if it's string-data, or std::vector<unsigned char> if it's just a bunch of binary bytes.

Upvotes: 4

Related Questions