Domanda

Let's say I have code like so:

#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

}

How do I reassure the compiler that writing MoreFields will not affect any invariants or will not do anything to invalidate the order of elements in the set?

If the only recourse is to use another container such as vector, how do I insert a new value in the sorted position while checking if one exists already?

È stato utile?

Soluzione

  • Declare MoreFields as mutable, or

  • const_cast the inchk.first expression to remove constness, or

  • encapsulate MoreFields within a const-qualified accessor that returns a non-const reference.

Altri suggerimenti

I would think you want to use a map instead of a set.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top