提问者:小点点

在C++向量构造中包含迭代器


在下面的代码中,它应该是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迭代器不一定在末尾,实际发生了什么? 我只见过第二个参数位于末尾的例子。


共2个答案

匿名用户

假设函数的参数如下所示:

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}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|向量|构造|中|包含|迭代|器)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?