【问题标题】:Accessing member via set's NON-const iterator that doesn't affect invariants通过不影响不变量的集合的 NON-const 迭代器访问成员
【发布时间】:2012-08-30 17:28:36
【问题描述】:

假设我有这样的代码:

#include <set>
#include <math.h>

typedef int OtherTypes;

struct MyType
{
    double Field1;
    OtherTypes MoreFields;

    MyType(double blah) :
        Field1(blah)
    {
    }

    bool operator < (const MyType &That) const
    {
        // Does not use any other member besides Field1
        return ( fabs(Field1 - That.Field1) > 1e-6 &&
                 Field1 < That.Field1 );
    }

};

int main()
{
    std::set<MyType> foo;
    std::pair< std::set<MyType>::iterator,
               bool > inchk = foo.insert(MyType(1.0));

    OtherTypes SomeVal = 1;
    if ( inchk.second )
        inchk.first->MoreFields = SomeVal; // error

}

如何向编译器保证编写 MoreFields 不会影响 任何不变量或不会做任何事情来使顺序无效 集合中的元素?

如果唯一的办法是使用另一个容器,例如vector,如何 我是否在检查是否有一个时在排序位置插入一个新值 已经存在?

【问题讨论】:

  • 如果您可以使用,我很确定 Boost.MultiIndex 可以解决您的问题。
  • @GManNickG -- 不幸的是,我的雇主不会使用它。非常感谢,还是一样。
  • 与您的问题无关,但您的operator&lt; 意味着您可以拥有abc 这样!(a &lt; b) &amp;&amp; !(b &lt; a) &amp;&amp; !(b &lt; c) &amp;&amp; !(c &lt; b),但仍然是a &lt; c
  • 欣赏另一篇帖子的链接,@interjay——我在发帖前进行了搜索,但没有找到您交叉引用的那个。也就是说,我的问题与其说是“为什么”(我理解),不如说是“如何”。此外,那里和这里(均由 James McNeillis!)接受的答案明显不同。

标签: c++ invariants const-iterator stdset


【解决方案1】:
  • MoreFields 声明为mutable,或

  • const_cast inchk.first 表达式来移除常量,或者

  • MoreFields 封装在一个返回非常量引用的 const 限定访问器中。

【讨论】:

    【解决方案2】:

    我认为您想使用地图而不是集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 2014-12-24
      • 2011-05-26
      • 2016-07-15
      相关资源
      最近更新 更多