0

I have the following C++ classes:

class MyClass {
private:
   int _id;
   unsigned long long _timestamp;
public:
   MyClass(int id, unsigned long long ts) : _id(id), _timestamp(ts) {}
   bool operator<(const MyClass& other) const { return _timestamp < other._timestamp; }
   int GetID() {return _id;}
};
class MyClass1 {
private:
    map<int, multiset<MyClass>> _list;
public:
    vector<int> GetMyClasses(int id, int count) {
        vector<int> result;
        transform(_list[id].rbegin(), _list[id].rbegin() + count, back_inserter(result), [](const MyClass& c) {return c.GetID();});
       return result;
    }
};

This is the build error:

1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xutility(1915,41): error C2676: binary '-': 'const _BidIt' does not define this operator or a conversion to a type acceptable to the predefined operator

I am using VS2019 Version 16.7.7. Any insight and advice is appreciated.

Kok How Teh
  • 3,298
  • 6
  • 47
  • 85

1 Answers1

0

You cannot increment an iterator of multiset by simple +.

Use std::advance to do it:

    auto it = _list[id].rbegin();
    auto it2 = it;
    std::advance(it2,count);
    transform(it, it2, 
        back_inserter(result), [](const MyClass& c) {return c.GetID();});

also GetID must be const method.

Demo

rafix07
  • 20,001
  • 3
  • 20
  • 33