I had a question on the Pramp platform. The task was to reverse words in a given string(a vector of chars). They expected a solution with no extra space, however the vector passed in the function was a 'const'.
vector<char> reverseWords(const vector<char>& arr )
So is there a way to modify a const vector? Or is there something that I don't get about const?
CodePudding user response:
You need to use a new vector inside the function which uses the values from the const vector, and then returns that.
vector<char> reverseWords(const vector<char>& arr )
{
vector<char> newArr;
// Do stuff with arr and newArr
...
return newArr;
}
CodePudding user response:
you can shoot yourself in foot via:
auto newVec = const_cast<vector<int>*>(&vec);
that means you are breaking your promise.
The right approach here as suggested by the others would be, to make your own copy and modify your copy.