C++ 通过set'访问成员;s非常量迭代器,该迭代器不';不影响不变量

C++ 通过set'访问成员;s非常量迭代器,该迭代器不';不影响不变量,c++,invariants,const-iterator,stdset,C++,Invariants,Const Iterator,Stdset,假设我有这样的代码: #include <set> #include <math.h> typedef int OtherTypes; struct MyType { double Field1; OtherTypes MoreFields; MyType(double blah) : Field1(blah) { } bool operator < (const MyType &Tha

假设我有这样的代码:

#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

}
#包括
#包括
typedef int其他类型;
结构MyType
{
双字段1;
其他类型更多领域;
我的类型(双重废话):
字段1(废话)
{
}
布尔运算符<(const MyType&That)const
{
//不使用除Field1之外的任何其他成员
返回(晶圆厂(场1-该场1)>1e-6&&
Field1inchk=foo.insert(MyType(1.0));
其他类型SomeVal=1;
如果(英寸秒)
inchk.first->MoreFields=SomeVal;//错误
}
如何向编译器保证编写更多字段不会影响性能 任何不变量或变量都不会使 集合中的元素

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

  • MoreFields
    声明为
    mutable
    ,或

  • const\u cast
    删除constness的
    inchk.first
    表达式,或

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

      • MoreFields
        声明为
        mutable
        ,或

      • const\u cast
        删除constness的
        inchk.first
        表达式,或

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


        • 我想你应该使用地图而不是集合

          我想你应该使用地图而不是集合

          如果你可以使用它,我很确定它能解决你的问题。可能是@GManNickG的副本——不幸的是,我的雇主不会使用它。尽管如此,还是非常感谢。与你的问题无关,但你的
          操作员非常欣赏另一篇文章的链接@interjay--我在发帖前搜索过,但没有找到你交叉引用的那篇。也就是说,我的问题不是“为什么”(我理解),而是“如何”。此外,这里和那里(都是詹姆斯·麦克尼利斯写的!)接受的答案有很大的不同。如果你能找到它,我很确定它能解决你的问题。可能是@GManNickG的副本——不幸的是,我的雇主不会使用它。尽管如此,还是非常感谢。与你的问题无关,但你的
          操作员非常欣赏另一篇文章的链接@interjay--我在发帖前搜索过,但没有找到你交叉引用的那篇。也就是说,我的问题不是“为什么”(我理解),而是“如何”。此外,这里和那里被接受的答案(都是詹姆斯·麦克尼利斯的!)有很大的不同。