简体   繁体   English

如何从向量中删除第一次出现的值?

[英]How do I remove the first occurrence of a value from a vector?

I'm trying to get a single element from a vector and push it to the back of the vector then remove it so I won't have an empty section in memory. 我正在尝试从向量中获取单个元素并将其推到向量的背面,然后将其删除,因此我在内存中不会有空的部分。 The erase-remove idiom can do this but it removes all instances of a particular value. 擦除删除惯用语可以做到这一点,但它会删除所有具有特定值的实例。 I just want the first one removed. 我只想删除第一个。

I'm not too experienced with standard library algorithms and I can't find the appropriate methods (if any) to do this. 我对标准库算法不太了解,因此找不到合适的方法(如果有)来执行此操作。 Here is an example: 这是一个例子:

int main() {
    std::vector<int> v{1, 2, 3, 3, 4};

    remove_first(v, 3);

    std::cout << v; // 1, 2, 3, 4
}

So how would I go about removing the first occurance of a 3 from this vector? 那么,如何从该向量中删除3的第一个出现?

Find it first, then erase it: 首先找到它,然后删除它:

auto it = std::find(v.begin(),v.end(),3);
// check that there actually is a 3 in our vector
if (it != v.end()) {
  v.erase(it);
}

If you don't care about maintaining the ordering of the elements in the vector, you can avoid the copy of the "tail" of remaining elements on erase: 如果您不关心保持向量中元素的顺序,则可以避免擦除时保留其余元素的“尾巴”:

auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end()) {
  std::iter_swap(it, v.end() - 1);
  v.erase(v.end() - 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM