在下面的代码中,它应该是Ranges::Rotate:
auto second(std::vector<int>& v, std::vector<int>::iterator new_first) -> std::vector<int>::const_iterator {
auto copy = std::vector<int>(v.begin(), new_first);
v.erase(v.begin(), new_first);
return v.insert(v.end(), copy.begin(), copy.end());
}
在函数的前两行中,newfirst迭代器不一定在末尾,实际发生了什么? 我只见过第二个参数位于末尾的例子。
假设函数的参数如下所示:
v : { 1, 2, 3, 4, 5}
new_first ^
然后这行:
auto copy = std::vector<int>(v.begin(), new_first);
使用vector
的构造函数,该构造函数需要2个迭代器来构造copy
变量:
v : { 1, 2, 3, 4, 5}
new_first ^
copy : {1, 2}
然后这行:
v.erase(v.begin(), new_first);
使用vector
的擦除方法删除初始元素:
v : { 3, 4, 5}
copy : {1, 2}
最后,这一行:
return v.insert(v.end(), copy.begin(), copy.end());
使用vector
的insert方法将初始元素(存储在copy
中)复制到v
的末尾,并将迭代器返回到第一个插入的元素:
v : { 3, 4, 5, 1, 2 }
return ^
有效实现旋转
。
auto copy = std::vector<int>(v.begin(), new_first);
您正在将第一个new_first-v.begin()
元素复制到名为copy
的新向量。
v.erase(v.begin(), new_first);
您正在从原始向量中擦除相同的new_first-v.begin()
元素。
v.insert(v.end(), copy.begin(), copy.end());
您正在将copy
的所有元素插入到原始向量中。 所以基本上您已经通过new_first-v.begin()
元素将向量v
向右旋转。
因此,如果您的v在开始时是{1,2,3,4,5}
,new_first点表示4
,则返回向量是{4,5,1,2,3}