【问题标题】:C++ multiset error C2676: binary '-': 'const _BidIt' does not define this operator or a conversion to a type acceptable to the predefined operatorC++ 多集错误 C2676:二进制“-”:“const _BidIt”未定义此运算符或转换为预定义运算符可接受的类型
【发布时间】:2021-02-14 22:06:43
【问题描述】:

我有以下 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 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

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

【问题讨论】:

    标签: visual-studio visual-c++ operator-overloading c++17 multiset


    【解决方案1】:

    您不能通过简单的 + 来增加 multiset 的迭代器。

    使用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

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 2020-10-10
      • 2020-12-20
      • 2013-02-11
      相关资源
      最近更新 更多