If I have a const vector defined in my class, how can I go about sorting it?
Attempting to sort a const vector will give errors since I'm changing the contents of a const vector.
You don't. If you need to modify it... well then it shouldn't be const. The two goals are in direct conflict with one another.
Instead of asking for a solution to a problem that doesn't make sense, tell us what you are actually trying to accomplish here. Are you trying to return a vector from a method that you don't want the caller to be able to modify? In that case, create a getter method and return a const vector&
#include <vector>
class Foo
{
public:
// clients can't change this vector directly
const std::vector<int>& get_vector() const { return _vec; }
// you can still create an interface that allows
// mutation of the vector in a safe way, or mutate
// the vector internally.
void push_back( int i ) { _vec.push_back( i ); }
private:
std::vector<int> _vec;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With