C++ 如何在C++中将数组中的所有元素初始化为相同的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2890598/
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
How to initialize all elements in an array to the same number in C++
提问by neuromancer
I'm trying to initialize an int array with everything set at -1.
我正在尝试初始化一个 int 数组,所有内容都设置为 -1。
I tried the following, but it doesn't work. It only sets the first value at -1.
我尝试了以下方法,但不起作用。它只将第一个值设置为 -1。
int directory[100] = {-1};
Why doesn't it work right?
为什么它不能正常工作?
回答by GManNickG
I'm surprised at all the answers suggesting vector
. They aren't even the same thing!
我对所有建议的答案感到惊讶vector
。他们甚至不是一回事!
Use std::fill
, from <algorithm>
:
使用std::fill
,来自<algorithm>
:
int directory[100];
std::fill(directory, directory + 100, -1);
Not concerned with the question directly, but you might want a nice helper function when it comes to arrays:
不直接关心这个问题,但是当涉及到数组时,您可能需要一个很好的辅助函数:
template <typename T, size_t N>
T* end(T (&pX)[N])
{
return pX + N;
}
Giving:
给予:
int directory[100];
std::fill(directory, end(directory), -1);
So you don't need to list the size twice.
所以你不需要两次列出大小。
回答by Arun
I would suggest using std::array
. For three reasons:
1. array provides runtime safety against index-out-of-boundin subscripting (i.e. operator[]
) operations,
2. array automatically carries the sizewithout requiring to pass it separately
3. And most importantly, array provides the fill()
method that is required for
this problem
我建议使用std::array
. 出于三个原因:
1. 数组在下标(即operator[]
)操作中提供针对索引越界的运行时安全性,
2. 数组自动携带大小而无需单独传递它
3. 最重要的是,数组提供了以下fill()
方法这个问题需要
#include <array>
#include <assert.h>
typedef std::array< int, 100 > DirectoryArray;
void test_fill( DirectoryArray const & x, int expected_value ) {
for( size_t i = 0; i < x.size(); ++i ) {
assert( x[ i ] == expected_value );
}
}
int main() {
DirectoryArray directory;
directory.fill( -1 );
test_fill( directory, -1 );
return 0;
}
Using array requiresuse of "-std=c++0x" for compiling (applies to the above code).
使用数组需要使用“-std=c++0x”进行编译(适用于上述代码)。
If that is not available or if that is not an option, then the other options like std::fill() (as suggested by GMan) or hand coding the a fill() method may be opted.
如果这不可用或不是一个选项,则可以选择其他选项,如 std::fill() (如GMan建议)或手动编码 a fill() 方法。
回答by Brian R. Bondy
If you had a smaller number of elements you could specify them one after the other. Array initialization works by specifying each element, not by specifying a single value that applies for each element.
如果您的元素数量较少,则可以一个接一个地指定它们。数组初始化的工作方式是指定每个元素,而不是指定适用于每个元素的单个值。
int x[3] = {-1, -1, -1 };
You could also use a vector and use the constructor to initialize all of the values. You can later access the raw array buffer by specifying &v.front()
您还可以使用向量并使用构造函数来初始化所有值。您可以稍后通过指定访问原始数组缓冲区&v.front()
std::vector directory(100, -1);
There is a C way to do it also using memset
or various other similar functions. memset
works for each char in your specified buffer though so it will work fine for values like 0
but may not work depending on how negative numbers are stored for -1
.
有一种 C 方法也可以使用memset
或 其他各种类似的函数来做到这一点。 memset
虽然适用于指定缓冲区中的每个字符,但它适用于类似的值,0
但可能无法工作,具体取决于-1
.
You can also use STL to initialize your array by using fill_n. For a general purpose action to each element you could use for_each.
您还可以使用 STL 通过使用fill_n来初始化您的数组。对于每个元素的通用操作,您可以使用 for_each。
fill_n(directory, 100, -1);
Or if you really want you can go the lame way, you can do a for loop with 100 iterations and doing directory[i] = -1;
或者如果你真的想要你可以走蹩脚的方式,你可以做一个 100 次迭代的 for 循环并做 directory[i] = -1;
回答by jopa
回答by Johnsyweb
It does work right. Your expectation of the initialiser is incorrect. If you really wish to take this approach, you'll need 100 comma-separated -1s in the initialiser. But then what happens when you increase the size of the array?
它确实工作正常。您对初始化程序的期望是不正确的。如果您真的希望采用这种方法,则需要在初始化程序中使用 100 个逗号分隔的 -1。但是当你增加数组的大小时会发生什么?
回答by Xavier Bigand
I had the same question and I found how to do, the documentation give the following example :
我有同样的问题,我找到了怎么做,文档给出了以下示例:
std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 (not in C++14)
So I just tried :
所以我只是试过:
std::array<int, 3> a1{ {1} }; // double-braces required in C++11 (not in C++14)
And it works all elements have 1 as value. It does not work with the = operator. It is maybe a C++11 issue.
它适用于所有元素都具有 1 作为值。它不适用于 = 运算符。这可能是一个 C++11 问题。
回答by T. K. Sah
u simply use for loop as done below:-
您只需按如下方式使用 for 循环:-
for (int i=0; i<100; i++)
{
a[i]= -1;
}
as a result as u want u can get A[100]={-1,-1,-1..........(100 times)}
结果如你所愿,你可以得到 A[100]={-1,-1,-1.........(100 次)}
回答by Satbir
use vector of int instead a array.
使用 int 向量代替数组。
vector<int> directory(100,-1); // 100 ints with value 1
回答by Mark Rushakoff
It is working right. That's how list initializers work.
它工作正常。这就是列表初始值设定项的工作方式。
I believe 6.7.8.10 of the C99 standard covers this:
我相信 C99 标准的 6.7.8.10 涵盖了这一点:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
- if it has pointer type, it is initialized to a null pointer;
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
- if it is an aggregate, every member is initialized (recursively) according to these rules;
- if it is a union, the first named member is initialized (recursively) according to these rules.
如果没有显式初始化具有自动存储持续时间的对象,则其值是不确定的。如果没有显式初始化具有静态存储持续时间的对象,则:
- 如果是指针类型,则初始化为空指针;
- 如果它有算术类型,则初始化为(正或无符号)零;
- 如果是聚合,则根据这些规则(递归地)初始化每个成员;
- 如果是联合,则根据这些规则(递归地)初始化第一个命名成员。
If you need to make all the elements in an array the same non-zero value, you'll have to use a loop or memset.
如果您需要使数组中的所有元素都具有相同的非零值,则必须使用循环或memset。
Also note that, unless you really know what you're doing, vectors are preferred over arrays in C++:
另请注意,除非您真的知道自己在做什么,否则在 C++ 中向量优先于数组:
Here's what you need to realize about containers vs. arrays:
- Container classes make programmers more productive. So if you insist on using arrays while those around are willing to use container classes, you'll probably be less productive than they are (even if you're smarter and more experienced than they are!).
- Container classes let programmers write more robust code. So if you insist on using arrays while those around are willing to use container classes, your code will probably have more bugs than their code (even if you're smarter and more experienced).
- And if you're so smart and so experienced that you can use arrays as fast and as safe as they can use container classes, someone else will probably end up maintaining your code and they'll probably introduce bugs. Or worse, you'll be the only one who can maintain your code so management will yank you from development and move you into a full-time maintenance role — just what you always wanted!
关于容器与数组,您需要了解以下几点:
- 容器类让程序员更有效率。因此,如果您坚持使用数组而周围的人愿意使用容器类,那么您的工作效率可能会低于他们(即使您比他们更聪明、更有经验!)。
- 容器类让程序员编写更健壮的代码。因此,如果您坚持使用数组而周围的人愿意使用容器类,那么您的代码可能会比他们的代码有更多的错误(即使您更聪明、更有经验)。
- 如果您非常聪明且经验丰富,可以像使用容器类一样快速和安全地使用数组,那么其他人可能最终会维护您的代码,并且他们可能会引入错误。或者更糟的是,您将是唯一可以维护您的代码的人,因此管理层会将您从开发中拉出来,让您担任全职维护角色——这正是您一直想要的!
There's a lot more to the linked question; give it a read.
链接的问题还有很多;给它一个阅读。
回答by Stephen
Can't do what you're trying to do with a raw array (unless you explicitly list out all 100 -1
s in the initializer list), you can do it with a vector
:
不能用原始数组做你想做的事(除非你-1
在初始化列表中明确列出所有 100 s),你可以用一个vector
:
vector<int> directory(100, -1);
Additionally, you can create the array and set the values to -1
using one of the other methods mentioned.
此外,您可以创建数组并将值设置为-1
使用提到的其他方法之一。