【问题标题】:Return element at index in a vector返回向量中索引处的元素
【发布时间】:2012-11-21 19:07:04
【问题描述】:

如何删除向量中指定索引处的元素,然后返回该元素? 有办法吗?

【问题讨论】:

  • 必须按照这个顺序吗?您可以使用operator[]at(),如果不是,则使用erase()
  • @Beginner,不是真的。它不是按值搜索,所以使用remove 有点没有意义。

标签: c++


【解决方案1】:

erase 可以删除指定索引处的元素,但不返回该元素。

你可以这样做:

aboutToBeErased = myVector.at(index);
myVector.erase(myVector.begin() + index);

但请注意,向量并不擅长删除不在向量末尾的元素。对于大型向量,这可能是一项代价高昂的操作。

【讨论】:

  • vector:erase 不接受 int 作为参数
  • 对于擦除行,我收到错误“IntelliSense:函数调用中的参数太少”
  • 应该是myVector.erase(std::next(myVector.begin(), index));
【解决方案2】:
  1. 要获取元素,可以使用std::vector::at()

    value = mVector.at(n);
    
  2. 要删除,std::vector::erase() 以下将删除项目编号。 n+1 并调整矢量大小。

    mVector.erase (mVector.begin()+n);
    

擦除会移动所有元素,因此,如果您确实擦除了中间的元素,则会进行索引。

【讨论】:

  • 提问者也想要这个元素。
【解决方案3】:

这是一个用 C++11 编写的函数,它将从向量中获取第 n 个元素并合理有效地擦除它:

template<typename Vector>
typename Vector::value_type getAndErase( Vector& vec, size_t index )
{
  Assert( index < vec.size() );
  typename Vector::value_type retval = std::move(vec[index]);
  vec.erase( vec.begin()+index );
  return retval;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多