1

I have two structs abc2 and abc

struct abc2 {
    const int& data;
    abc2(const int& cdata) : data(cdata) {}
};

struct abc {
    const int &data;
    abc(const int& cdata) : data(cdata) {}

    bool operator <(const abc2& rhs) const {
        return data < rhs.data;
    }
};

And I have a map of abc and int

std::map<abc, int> test;
test[abc(1)] = 2;
test[abc(2)] = 3;

And I want to search test with struct abc2. I assumed it would work because I have overloaded the < operator in abc to accept abc2

auto foo = test.find(abc2(1));

However this does not work, and I get a compile time error saying cannot convert argument 1 from 'abc2' to 'const abc &'

Is there a workaround for achieving this? It is essential that I achieve the lookup using abc2.

Tom
  • 1,235
  • 9
  • 22
  • You need to give `abc2` a default constructor: `abc2() = default;`. `test[abc(1)]` already constructs a `abc2` instance using the default constructor. – πάντα ῥεῖ Nov 09 '20 at 21:04
  • Instead of operator < what if you made a copy constructor that accepted abc2? – Jerry Jeremiah Nov 09 '20 at 21:07
  • The value type (`int`) is default constructible, this dupe doesn't apply – Artyer Nov 09 '20 at 21:09
  • Also the answer is to use a transparent comparator like `std::less`, and add a reverse comparison too (`abc2 < abc`), and this code snippet will work – Artyer Nov 09 '20 at 21:10
  • I don't think `test[abc(1)] = 2; test[abc(2)] = 3;` does what you think it does because abc holds data by reference so when you run ``test[abc(1)] = 2; test[abc(2)] = 3;`` you still have only one item in the map. – Jerry Jeremiah Nov 09 '20 at 21:22

0 Answers0