删除向量 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:34:32  来源:igfitidea点击:

Remove all elements in vector C++

c++vectorerase

提问by thisiscrazy4

Possible Duplicate:
Delete all items from a c++ std::vector

可能的重复:
从 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 vectorto myVector. It is not a good idea to use the name of a class for an instance.

我已将实例名称从 更改vectormyVector. 将类的名称用于实例并不是一个好主意。

回答by Pubby

std::vectorhas a clearmember, you know:

std::vectorclear会员,你知道:

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 vectoris 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.

所以你不需要迭代。