milo
milo

Reputation: 1220

map with non-standard key. what's wrong?

I'm trying to write std::map container where key has 2 values. Here is the example:

#include <map>
#include <iostream>

using namespace std;

struct Key {
    int i1; 
    int i2; 

    struct Comparator {
        bool operator() (const Key& k1, const Key& k2) {
            if (k1.i1 < k2.i1)
                return true;
            else if (k1.i2 < k2.i2)
                return true;

            return false;
        }   
    };  
};

int main() {
    std::map<Key, int, Key::Comparator> tree;

    for (int i = 0; i < 100; ++i) {
        for (int j = 0; j < 10; ++j) {
            Key key = {i, j}; 

            tree[key] = i * j;
        }   
    }   
    cout << "tree size: " << tree.size() << endl;

    Key key = {45, 3}; 

    std::map<Key, int, Key::Comparator>::iterator it = tree.find(key);
    if (it == tree.end()) {
        cout << "nothing has found" << endl;
        return 1;
    }   

    cout << "value: " << it->second << endl;

    return 0;
}

It says me "nothing has found". Where did i make mistake? How should i write Comparator to make it work properly? Thank you.

Upvotes: 4

Views: 227

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

Consider that with your comparator, both of the following are true:

Key(1,2) < Key(2,1)
Key(2,1) < Key(1,2)

You could use a lexicographical order:

return (k1.i1 != k2.i1) ? (k1.i1 < k2.i1)
                        : (k1.i2 < k2.i2);

Upvotes: 6

Related Questions