【问题标题】:Erase range from a std::vector?从 std::vector 擦除范围?
【发布时间】:2011-07-17 01:20:35
【问题描述】:

如果我的std::vector 有 100 个元素,而我只想保留前 10 个并删除其余的,有没有方便的方法来做到这一点?

【问题讨论】:

    标签: c++


    【解决方案1】:

    是的,有一个 erase 函数接受 first 和 last 的参数。

    v.erase(v.begin() + 10, v.end());
    

    【讨论】:

      【解决方案2】:
      vec.resize(10); // drops the rest (capacity remains the same)
      

      【讨论】:

      • 如果元素没有默认构造函数,这将不起作用。
      【解决方案3】:

      vec.erase(vec.begin() + 10, vec.begin() + 100);

      【讨论】:

        【解决方案4】:
        theVector.erase(theVector.begin() + 10, theVector.begin() + 100);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-12-13
          • 2011-08-30
          • 2011-10-24
          • 2018-12-05
          • 2011-05-09
          • 1970-01-01
          • 2016-03-31
          相关资源
          最近更新 更多