4

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.

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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}{}
    };

Comments

0

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 } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.