删除向量 C++ 中的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13640217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all elements in vector C++
提问by thisiscrazy4
Possible Duplicate:
Delete all items from a c++ std::vector
I think using begin in an iterator is messing this up since it's only iterating 26 times and skipping every 2 elements. How else can I do it?
我认为在迭代器中使用 begin 会把它搞砸,因为它只迭代 26 次并且每 2 个元素跳过一次。我还能怎么做?
void clearVector() {
for (int i = 0; i < 52; i++) {
vector.erase(vector.begin() + i);
}
}
回答by juanchopanza
You call the std::vector::clear()
method:
您调用该std::vector::clear()
方法:
myVector.clear();
where I have changed the instance name from vector
to myVector
. It is not a good idea to use the name of a class for an instance.
我已将实例名称从 更改vector
为myVector
. 将类的名称用于实例并不是一个好主意。
回答by Pubby
std::vector
has a clear
member, you know:
std::vector
有clear
会员,你知道:
void clearVector() {
vector.clear();
}
Anyway, since you're erasing from the left the size will be shrinking also. This works the way you intend, although it is inefficient because it will have to do O(N) copies towards the front each iteration.
无论如何,由于您是从左侧擦除,因此尺寸也会缩小。这会按照您的预期工作,尽管它效率低下,因为每次迭代都必须向前端进行 O(N) 次复制。
void clearVector() {
for (int i = 0; i < 52; i++) {
vector.erase(vector.begin());
}
}
回答by billz
You can use std::vector::clear() to clear elements or swap with an empty container is much faster.
您可以使用 std::vector::clear() 清除元素或与空容器交换要快得多。
vec.clear();
or
或者
std::vector<DataType>().swap(vec);
Note: your variable vector
is not good variable name, better change it to something else.
注意:您的变量vector
不是好的变量名,最好将其更改为其他名称。
回答by ShinTakezou
vec.erase(vec.begin() /* first you want delete */,
vec.begin() + vec.size() /* 1 beyond the last you want to delete */);
// or if you have to erase all elements:
vec.clear();
so you don't need to iterate.
所以你不需要迭代。