设置动态数组的默认值

时间:2021-07-24 17:43:02

This code will create an array of 100 elements and set the value of each to false.

此代码将创建一个包含100个元素的数组,并将每个元素的值设置为false。

bool boolArray[100] = false;

How can I set the default value of a dynamic array?

如何设置动态数组的默认值?

void Foo(int size)
{
    bool boolArray = new bool[size];
    //Now what?
}

4 个解决方案

#1


11  

In standard C++ you can default-initialize just about anything, including that array:

在标准C ++中,您可以默认初始化任何内容,包括该数组:

bool* boolArray = new bool[size]();     // Zero-initialized

Complete program that also checks the result, and deallocates the array:

完成程序,也检查结果,并释放数组:

bool foo( int size )
{
    bool* boolArray = new bool[size]();     // Zero-initialized

    // Check that it is indeed zero-initialized:   
    for( int i = 0; i < size; ++i )
    {
        if( boolArray[i] ) { delete[] boolArray; return false; }
    }
    delete[] boolArray; return true;
}

#include <iostream>
int main()
{
    using namespace std;
    cout << (foo( 42 )? "OK" : "Ungood compiler") << endl;
}

Whether your compiler will accept or even do the Right Thing is another matter.

你的编译器是否会接受甚至做正确的事情是另一回事。

So, in practice, if you feel an irresistible urge to use a raw array, then perhaps better use std::fill or some such, or even a raw loop.

所以,在实践中,如果你觉得使用原始数组的不可抗拒的冲动,那么也许最好使用std :: fill或者其他一些,甚至是原始循环。

But note the repeated delete[]-expressions. Such redundant code is very easy to get wrong: it's Evil™. And there's much else that can go wrong with use of raw arrays, so as a novice, just Say No™ to raw arrays and raw pointers and such.

但请注意重复删除[] - 表达式。这样的冗余代码很容易出错:它是Evil™。使用原始数组还有很多其他问题,所以作为一个新手,只需对原始数组和原始指针等等。

Instead, use standard library containers, which manage allocation, initialization, copying and deallocation for you – correctly. There is a little problem with that, though, namely a premature optimization in std::vector<bool>, which otherwise would be the natural choice. Essentially std::vector<bool> uses just one bit per value, so that it can't hand out references to bool elements, but instead hands out proxy objects…

相反,使用标准库容器,它可以正确地管理分配,初始化,复制和释放。但是,这有点问题,即std :: vector 中的过早优化,否则这将是自然的选择。基本上std :: vector 每个值只使用一位,因此它不能分发对bool元素的引用,而是分发代理对象......

So, for bool elements, use e.g. a std::bitset (when the size is known at compile time), or e.g. a std::deque, as follows:

因此,对于bool元素,使用例如std :: bitset(当编译时知道大小时),或者例如std :: deque,如下:

#include <deque>

bool foo( int size )
{
    std::deque<bool> boolArray( size );     // Zero-initialized

    for( int i = 0; i < size; ++i )
    {
        if( boolArray[i] ) { return false; }
    }
    return true;
}

#include <iostream>
int main()
{
    using namespace std;
    cout << (foo( 42 )? "OK" : "Ungood compiler") << endl;
}

Cheers & hth.,

干杯&hth。,

#2


11  

Use std::fill function or std::fill_n function.

使用std :: fill函数或std :: fill_n函数。

std::fill_n(boolArray, length, defaultValue);
std::fill(boolArray, boolArray + length, defaultValue);

Side note: try using std::vector instead.

旁注:尝试使用std :: vector代替。

#3


2  

bool* boolArray = new bool[size];
for(int i = 0; i < size; i++) {
    boolArray[i] = false;
}

#4


0  

What about:

void Foo(int size)
{
    // bool boolArray = new bool[size];
    // Did you mean bool*?
    // Try and avoid direct allocation of memory.
    // Memory allocation should be done inside an object that 
    // actively manages it.

    // Normally I would recommend a vector
    std::vector<bool>   boolArray(size, false);

    // But. And a Big but. Is that the standards committee decided to
    // specialize the vector for bool so that each element only takes
    // a single bit. Unfortunately this had some side effects that were
    // made its use not perfect (time/assign-ability).

    // So we can try a boost array
    boost::array<bool, size>   boolArray;
}

#1


11  

In standard C++ you can default-initialize just about anything, including that array:

在标准C ++中,您可以默认初始化任何内容,包括该数组:

bool* boolArray = new bool[size]();     // Zero-initialized

Complete program that also checks the result, and deallocates the array:

完成程序,也检查结果,并释放数组:

bool foo( int size )
{
    bool* boolArray = new bool[size]();     // Zero-initialized

    // Check that it is indeed zero-initialized:   
    for( int i = 0; i < size; ++i )
    {
        if( boolArray[i] ) { delete[] boolArray; return false; }
    }
    delete[] boolArray; return true;
}

#include <iostream>
int main()
{
    using namespace std;
    cout << (foo( 42 )? "OK" : "Ungood compiler") << endl;
}

Whether your compiler will accept or even do the Right Thing is another matter.

你的编译器是否会接受甚至做正确的事情是另一回事。

So, in practice, if you feel an irresistible urge to use a raw array, then perhaps better use std::fill or some such, or even a raw loop.

所以,在实践中,如果你觉得使用原始数组的不可抗拒的冲动,那么也许最好使用std :: fill或者其他一些,甚至是原始循环。

But note the repeated delete[]-expressions. Such redundant code is very easy to get wrong: it's Evil™. And there's much else that can go wrong with use of raw arrays, so as a novice, just Say No™ to raw arrays and raw pointers and such.

但请注意重复删除[] - 表达式。这样的冗余代码很容易出错:它是Evil™。使用原始数组还有很多其他问题,所以作为一个新手,只需对原始数组和原始指针等等。

Instead, use standard library containers, which manage allocation, initialization, copying and deallocation for you – correctly. There is a little problem with that, though, namely a premature optimization in std::vector<bool>, which otherwise would be the natural choice. Essentially std::vector<bool> uses just one bit per value, so that it can't hand out references to bool elements, but instead hands out proxy objects…

相反,使用标准库容器,它可以正确地管理分配,初始化,复制和释放。但是,这有点问题,即std :: vector 中的过早优化,否则这将是自然的选择。基本上std :: vector 每个值只使用一位,因此它不能分发对bool元素的引用,而是分发代理对象......

So, for bool elements, use e.g. a std::bitset (when the size is known at compile time), or e.g. a std::deque, as follows:

因此,对于bool元素,使用例如std :: bitset(当编译时知道大小时),或者例如std :: deque,如下:

#include <deque>

bool foo( int size )
{
    std::deque<bool> boolArray( size );     // Zero-initialized

    for( int i = 0; i < size; ++i )
    {
        if( boolArray[i] ) { return false; }
    }
    return true;
}

#include <iostream>
int main()
{
    using namespace std;
    cout << (foo( 42 )? "OK" : "Ungood compiler") << endl;
}

Cheers & hth.,

干杯&hth。,

#2


11  

Use std::fill function or std::fill_n function.

使用std :: fill函数或std :: fill_n函数。

std::fill_n(boolArray, length, defaultValue);
std::fill(boolArray, boolArray + length, defaultValue);

Side note: try using std::vector instead.

旁注:尝试使用std :: vector代替。

#3


2  

bool* boolArray = new bool[size];
for(int i = 0; i < size; i++) {
    boolArray[i] = false;
}

#4


0  

What about:

void Foo(int size)
{
    // bool boolArray = new bool[size];
    // Did you mean bool*?
    // Try and avoid direct allocation of memory.
    // Memory allocation should be done inside an object that 
    // actively manages it.

    // Normally I would recommend a vector
    std::vector<bool>   boolArray(size, false);

    // But. And a Big but. Is that the standards committee decided to
    // specialize the vector for bool so that each element only takes
    // a single bit. Unfortunately this had some side effects that were
    // made its use not perfect (time/assign-ability).

    // So we can try a boost array
    boost::array<bool, size>   boolArray;
}