保持长度不变并将空槽设置为 0 的 vector 线性移位的最佳方法是什么,就像 valarray.shift(int n)
所做的那样。
我能想到一个幼稚的方法,只是想知道是否有更好的方法
int shift = 2;
std::vector<int> v = {1,2,3,4,5};
std::rotate(v.begin(), v.end() - shift, v.end());
std::fill(v.begin(), v.begin() + shift, 0);
// Input: 1,2,3,4,5
// Output: 0,0,1,2,3
最佳答案
你可以使用 std::move
相反,因为它可能比 std::rotate
更“高效”。不过仍然需要 std::fill
调用。
像这样使用
std::move(begin(v), end(v) - shift, begin(v) + shift);
std::fill(begin(v), begin(v) + shift, 0);
此外,如果 vector 的位移或大小是从程序外部输入的,那么不要忘记添加一些安全检查(如 the answer by Paolo 中)。
关于c++ - vector 的高效移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52288372/