Reputation: 741
I have the following struct
in a vector
struct ub_node {
const size_t index;
const double ub_dist;
bool operator<(const ub_node &rhs) const { return ub_dist< rhs.ub_dist; }
};
I would like to sort that vector
. I have tried using std::sort
but I get a compile error:
error: use of deleted function ‘ub_node& ub_node::operator=(ub_node&&)’
with a reference to the line where I do std::sort(result.begin(), result.end());
, where result
is of type vector<ub_node>
.
As far as I understand, the const
does NOT affect the execution time, but merely ensures that the programmer (me) does not do anything stupid. If this is the case, I might remove the const
and try to ensure that I do not change the node afterwards. Can someone confirm this? Or help me to sort it?
Upvotes: 3
Views: 836
Reputation: 171303
As far as I understand, the const does NOT affect the execution time, but merely ensures that the programmer (me) does not do anything stupid.
Correct.
Sorting a vector swaps the elements around, which is not possible if the elements have immutable data (with your ub_node
type you can't even remove or insert an element anywhere except the end of the vector, because that also needs to modify existing elements).
I suggest you remove the const
from your members, so the type is possible to modify, and then structure your code so that parts of the program which shouldn't modify it only interacts with the class through const ub_node&
or const ub_node*
.
That means that the class is modifiable when necessary, but won't be modified by parts of the program that aren't supposed to modify it.
Upvotes: 3