C++ Standard: Unexpected const_iterator in multiset

前端 未结 2 1663
执念已碎
执念已碎 2021-01-05 03:10

I recently ran into an odd issue where I\'d get a const_iterator instead of the expected iterator when iterating through a multiset. It turned out

2条回答
  •  庸人自扰
    2021-01-05 04:11

    How to fool the compiler for std::set::iterator?

    I have struct

    struct _item {
      int a;
      int b;
      bool operator <(const _item& x) const {return a

    I want change only member b (b is irrelevant for sorting in set, only member a is compared).

    std::set<_item> data;
    std::set<_item>::iterator iter=data.begin();
    iter->b=0;  // error !!!
    

    Avada Kedavra !

    struct _item {
      int a;
      int b;
      _item* self;
      _item() {self=this;} 
      bool operator <(const _item& x) const {return aself->b=0; // Success !! Tested on VC10
    

    Of course more C + + correctly

    struct _item {
      int a;
      int b;
     private:
      _item* self;
     public:
      _item() {self=this;} 
      bool operator <(const _item& x) const {return ab;}
    };
    std::set<_item> items;
    std::set<_item>::iterator iter=items.begin();
    iter->bReference()=0; // Success !! Tested on VC1
    

提交回复
热议问题