简体   繁体   中英

Modifying constant vector in C++

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM