Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you sort a const vector?

Tags:

c++

vector

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.

like image 404
cody Avatar asked Dec 05 '25 10:12

cody


1 Answers

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;
}
like image 196
Ed S. Avatar answered Dec 08 '25 14:12

Ed S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!