STL sets are designed so that it is not possible to modify the elements in the set (with good reason, see stackoverflow). Suppose however I have a structure in which only one of the members acts as the key. Is there an alternative data structure to a set. I really want exactly the behavior of sets except this inability to modify a field or member which is non-key.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- C#中 public virtual string Category { get; }这么写会报错:
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
Declare the non-key as
mutable
, then you would be able to modify it.You've to make sure that
nonkey
is really a non-key; it must not take part inoperator<
comparison function.May be it's time to redesign, considering std::map instead of std::set.
instead of
consider
you can then do
A few possibilities come to mind:
I'd look at the first two options as preferable; the last should be used only if you can't adapt your problem or existing STL containers to meet your needs.
There is no way to enforce that members of the class used in the ordering predicate are not modified. An modification to members used in the ordering predicate may potentially break the set.
The easy way to trick the compiler into letting you use the set with mutable members is marking the members as mutable:
Then, you have to manually ensure that
Foo::operator<()
never usesmyVal2
in the comparison. This is possible, but is is a Bad Idea (tm). You can mark this specific operator with a huge comment, but you can't automatically duplicate this comment into all custom comparison functions (std::set<>
accepts this as a second parameter).The real way to achieve what you want is to use a
std::map<>
. Put the "key" part in the key and the "value" part in the value.