如何使用 new 在 C++ 中创建数组并初始化每个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4654431/
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 do I create an array in C++ using new and initialize each element?
提问by B Seven
Without iterating through each element, how do I create an array using new and initialize each element to a certain value?
在不遍历每个元素的情况下,如何使用 new 创建数组并将每个元素初始化为某个值?
bool* a = new bool[100000];
Using VS 2008.
使用 VS 2008。
Thanks!
谢谢!
回答by rchanley
In addition to what GMan said above, I believe you can specify an initial value for each value in your vector on construction like this..
除了 GMan 上面所说的之外,我相信您可以在构建时为向量中的每个值指定一个初始值。
vector<bool> a (100000, true);
回答by GManNickG
In that case, the only value you can set it to is false
with:
在这种情况下,您可以将其设置为的唯一值是false
:
bool* a = new bool[100000]();
That said, I'm not sure why you'd think you can't use a loop. They're there for a reason. You should just use the ready-made function fill
or fill_n
(depending on taste).
也就是说,我不确定为什么你认为你不能使用循环。他们在那里是有原因的。您应该只使用现成的功能fill
或fill_n
(取决于口味)。
Note using new
"raw" like that is terrible programming practice. Use a std::vector<bool>
*:
请注意,new
像这样使用“原始”是糟糕的编程实践。使用std::vector<bool>
*:
std::vector<bool> v;
v.resize(100000);
std::fill(v.begin(), v.end(), true); // or false
Or:
或者:
std::vector<bool> v;
v.reserve(100000);
std::fill_n(std::back_inserter(v), 100000, true); // or false
*Of course, std::vector<bool>
happens to break the proper container interface so doesn't actually store bool
's. If that's a problem use a std::vector<char>
instead.
*当然,std::vector<bool>
碰巧破坏了正确的容器接口,因此实际上并不存储bool
's. 如果这是一个问题,请改用 a std::vector<char>
。
回答by Edward Strange
You should prefer the vector approach, but you can also use memset.
您应该更喜欢矢量方法,但您也可以使用 memset。
回答by Mahesh
If 0 is false
and 1 is true
considered - you can do
如果0 is false
并1 is true
考虑 - 你可以做
bool* a = new bool[100];
std::fill_n( a, 100, 1 ); // all bool array elements set to true
std::fill_n( a, 100, 0 ); // all bool array elements set to false