[英]Modifying constant vector in C++
I had a question on the Pramp platform.我在 Pramp 平台上有一个问题。 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'.他们期望一个没有额外空间的解决方案,但是在函数中传递的向量是一个“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?或者我对 const 有什么不明白的地方?
You need to use a new vector inside the function which uses the values from the const vector, and then returns that.您需要在函数内部使用一个新向量,该向量使用来自 const 向量的值,然后返回该向量。
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.其他人建议的正确方法是制作您自己的副本并修改您的副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.