cody
cody

Reputation: 157

How can you sort a const 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.

Upvotes: 1

Views: 11686

Answers (3)

Tanmoy Datta
Tanmoy Datta

Reputation: 1644

Yes, you can sort a const vector in C++.

Let a const vector is v.

const vector<int> v={5,4,3,2,1};

If you want to sort this vector using sort(v.begin(),v.end()) then it will result some runtime error due to violation of const.

But Here is the magic-

vector<int>*temp=(vector<int>*)&v;
sort(temp->begin(),temp->end());

You can sort the vector v using another vector pointer and referencing it to that.

After this, if you print the vector v then you will get output like this -

for(int a:v)
    cout<<a<<" ";
cout<<endl;

Output: 1 2 3 4 5

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124692

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;
}

Upvotes: 4

Jon G.
Jon G.

Reputation: 126

Is it the vector that's const? Or the data inside it that needs to be const?

If you have a const vector, then there's probably a reason why it shouldn't be modified....

That being said. Here's pseudocode on how you can shoot yourself in the foot:

const std::vector< Foo* > v;  // hypothetical declaration
std::vector< Foo* >* vPtr = const_cast< std::vector< Foo* >* >(&v);
// GOOD LUCK
(*vPtr)[0] = new Foo(); 

Upvotes: 4

Related Questions