C++ 多重集错误 C2676:二进制“-”:'const _BidIt' 未定义此运算符或预定义运算符可接受的类型的转换

C++ multiset error C2676: binary '-': 'const _BidIt' does not define this operator or a conversion to a type acceptable to the predefined operator

我有以下 C++ 类:

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;
    }
};

这是构建错误:

1>C:\Program Files (x86)\Microsoft Visual Studio19\Community\VC\Tools\MSVC.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

我使用的是 VS2019 版本 16.7.7。感谢任何见解和建议。

您不能通过简单的 +.

增加多重集的迭代器

使用std::advance来做:

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

GetID必须是const方法。

Demo