如何从向量中删除第一次出现的值? [英] 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
}
那么我该如何删除
推荐答案
先找到它,然后将其删除:
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);
}
这篇关于如何从向量中删除第一次出现的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文