简体   繁体   中英

How to set 2d array with same values using initializer in constructor?

I have a 2D array, and I want to use initializer to initialize it in my constructor. I want all of my array elements to have the same values. This is what I have:

private:
    struct Something {
        string x
        double y;
        int z;
    };
    Something array[50][50];

class::class() : array{ "wow", 2.4, 8 } {
}

I have tried method above in my code but was only assigning the first element to be what I want. Should I assign every element by using loop with the initializer along? Thank you.

Just use an initializer list in the default constructor:

Live sample

struct Something {
private:
    string x;
    double y;
    int z;
public:
    Something() : x("wow"), y(2.4), z(8){}
};

Note that your private access modifier is in an odd place, place it inside the class/struct.

you can have a constructor for struct object with default initialization. something like this,

struct Something {
        string x;
        double y;
        int z;
        Something() : x { "wow" }, y{ 2.4 }, z{8}{}
    };

You can use the standard algorithm std::fill the following way.

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

struct A
{
    struct B
    {
        std::string x;
        double y;
        int z;
    } a[5][5];

    A()
    {
        B ( &ra )[25] = reinterpret_cast<B ( & )[25]>( a );
        std::fill( std::begin( ra ), std::end( ra ), B{"wow", 2.4, 8 } );
    }       
};


int main() 
{
    A a;

    for ( const auto &row : a.a )
    {
        for ( const auto &item : row )
        {
            std::cout << "{ " << item.x << ", " << item.y << ", " << item.z << " } ";
        }
        std::cout << '\n';
    }

    return 0;
}

The program output is

{ wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } 
{ wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } 
{ wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } 
{ wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } 
{ wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } { wow, 2.4, 8 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM