简体   繁体   English

在 C++ 类中初始化二维数组

[英]Initializing 2D Array in A Class C++

I am trying to initialize nums 2D array in a Class Construct .我正在尝试在 Class Construct初始化nums二维数组。 I am using the default constructor to initialize it but since it has already been created I am unable to.我正在使用默认构造函数来初始化它,但由于它已经创建,我无法。 I cannot initialize it in the class either.我也无法在课堂上初始化它。 I have tried initializing each element manually and it works but I want to just initialize nums in one line.我尝试手动初始化每个元素并且它可以工作,但我只想在一行中初始化nums

#include <iostream> 
using namespace std; 

class Construct { 
public: 
    int nums[3][3]; 

    // Default Constructor 
    construct() 
    { 
        int nums[3][3] = {{4,5,42,34,5,23,3,5,2}}
    } 
}; 

int main() 
{ 

    Construct c; 
    cout << "a: " << c.nums[1][0] << endl 
        << "b: " << c.nums[0][1]; 
    return 1; 
} 

I have tried nums[1][0] = 5 ... but that is not very efficient.我试过nums[1][0] = 5 ... 但这不是很有效。 Any feedback would be great.任何反馈都会很棒。

Use initializer list使用初始化列表

Construct(): nums {{4,5,42},{34,5,23},{3,5,2}}
{ }

In case you want to be able to inititalize your class with custom values, you will need to provide a constructor that takes some kind of a container as an argument and uses it to initialize your array: ie Construct(const atd::array<int, 6>&) .如果您希望能够使用自定义值初始化您的类,您将需要提供一个构造函数,该构造函数将某种容器作为参数并使用它来初始化您的数组: ie Construct(const atd::array<int, 6>&)

But to avoid the overhead of rewriting all the values of an already initialized array, you will need to use a Pack expansion.但是为了避免重写已初始化数组的所有值的开销,您将需要使用 Pack 扩展。

Here is a customized class template that provides such a constructor:这是一个自定义的类模板,它提供了这样一个构造函数:

#include <utility>
#include <array>

// typename of an underlying array, sz0 and sz1 - array dimensions
template <typename T, size_t sz0, size_t sz1,
    class = decltype(std::make_index_sequence<sz0 + sz1>())>
    class Construct_;

// expanding a Pack of indexes to access std::array's variables
template <typename T, size_t sz0, size_t sz1,
    size_t ... indx>
    class Construct_<T, sz0, sz1, 
        std::index_sequence<indx...>>
{
// make it private or use a struct instead of a class
    T nums_[sz0][sz1];

public:

    // nums_ is initialized with arr's values. No additional copies were made
    Construct_(const std::array<T, sz0 + sz1> &arr)
        : nums_{ arr[indx] ... }
    {}

};

using Construct33int = Construct_<int, 3, 3>;

int main()
{
    std::array<int, 6> arr{ 4, 8, 15, 16, 23, 42 };
    Construct33int c{ arr };

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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