如何清除 C++ 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13308216/
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:10:41  来源:igfitidea点击:

How do I clear a C++ array?

c++visual-c++

提问by Jiew Meng

How do I clear/empty a C++ array? Theres array::fill, but looks like its C++11 only? I am using VC++ 2010. How do I empty it (reset to all 0)?

如何清除/清空 C++ 数组?有array::fill,但看起来只有 C++11?我正在使用 VC++ 2010。如何清空它(重置为全 0)?

回答by Angew is no longer proud of SO

std::fill_n(array, elementCount, 0);

Assuming arrayis a normal array (e.g. int[])

假设array是一个普通数组(例如int[]

回答by juanchopanza

Assuming a C-style array aof size N, with elements of a type implicitly convertible from 0, the following sets all the elements to values constructed from 0.

假设一个a大小为 的 C 样式数组N,其元素类型可从 隐式转换0,以下将所有元素设置为从 构造的值0

std::fill(a, a+N, 0);

Note that this is not the same as "emptying" or "clearing".

请注意,这与“清空”或“清除”不同。

Edit: Following james Kanze's suggestion, in C++11 you could use the more idiomatic alternative

编辑:按照 James Kanze 的建议,在 C++11 中,您可以使用更惯用的替代方法

std::fill( std::begin( a ), std::end( a ), 0 );

In the absence of C++11, you could roll out your own solution along these lines:

在没有 C++11 的情况下,您可以按照以下方式推出自己的解决方案:

template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }

template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }

std::fill( begin_( a ), end_( a ), 0 );

回答by Michael Krelin - hacker

std::fill(a.begin(),a.end(),0);

回答by Neil McGill

Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize

如果你想用值以外的东西来清除数组,std::file 不会削减它;相反,我发现 std::generate 很有用。例如,我有一个要初始化的列表向量

std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });

You can do ints too e.g.

你也可以做整数,例如

std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

or just

要不就

std::generate(v.begin(), v.end(), [] (){ return 0; });

but I imagine std::fill is faster for the simplest case

但我想 std::fill 在最简单的情况下会更快

回答by riti

Hey i think The fastest way to handle that kind of operation is to memset() the memory.

嘿,我认为处理这种操作的最快方法是 memset() 内存。

Example-

例子-

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

A similar C++ way would be to use std::fill

类似的 C++ 方法是使用 std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

回答by Denis Ermolin

If only to 0 then you can use memset:

如果只有 0 那么你可以使用memset

int* a = new int[6];

memset(a, 0, 6*sizeof(int));