【问题标题】:including an iterator in c++ vector construction在 C++ 向量构造中包含一个迭代器
【发布时间】:2020-06-14 12:43:31
【问题描述】:

在下面的代码中,应该是 range::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());
}

new_first 迭代器不一定在最后的函数的前 2 行实际发生了什么?我只见过第二个参数特别位于末尾的示例。

【问题讨论】:

    标签: c++ vector iterator


    【解决方案1】:

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

    v : { 1, 2, 3, 4, 5}
      new_first ^
    

    然后这一行:

    auto copy = std::vector<int>(v.begin(), new_first);
    

    使用 vectorconstructor 需要 2 个迭代器来构造 copy 变量:

    v : { 1, 2, 3, 4, 5}
      new_first ^
    copy : {1, 2}
    

    然后这一行:

    v.erase(v.begin(), new_first);
    

    使用vectorerase方法去除初始元素:

    v : { 3, 4, 5}
    copy : {1, 2}
    

    最后,这一行:

    return v.insert(v.end(), copy.begin(), copy.end());
    

    使用vectorinsert方法将初始元素(存储在copy)复制到v的末尾,并返回一个迭代器到第一个插入的元素:

    v : { 3, 4, 5, 1, 2 }
            return ^          
    

    有效实施rotate

    【讨论】:

      【解决方案2】:
      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 的所有元素插入到原始向量中。所以基本上你已经将矢量v 向右旋转了new_first - v.begin() 元素。

      因此,如果你的 v 开头是 {1,2,3,4,5} 并且 new_first 指向说 4,那么返回向量是 {4,5,1,2,3}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-29
        • 1970-01-01
        • 2015-02-19
        • 2012-11-19
        • 2020-01-21
        • 2021-10-08
        • 1970-01-01
        • 2023-02-22
        相关资源
        最近更新 更多