如何在 C++ 中分配二维初始值设定项列表?

And*_*rey 0 c++ vector initializer-list

我从向量继承了我的类,我希望能够像向量一样将列表分配给我的类。

我的代码如下:

#include <vector>
using namespace std;

template<typename T>
class Matrix
    : public vector<vector<T>>
{
public:
    Matrix( vector<vector<T>> && m )
        : vector<vector<T>>( m )
    {}

    // Tried this approach, but it doesn't work
    // Matrix(std::initializer_list<std::initializer_list<T>> l){
    // }
}

int main()
{
  Matrix<int> m({{0, 1}, {2, 3}}); // it works
  // Matrix<int> m = {{0, 1}, {2, 3}}; // error: no instance of constructor "Matrix<T>::Matrix [with T=int]" matches the argument list -- argument types are: ({...}, {...})
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*k R 5

只需将std::vector构造函数引入您的类范围:

template <typename T> class Matrix : public vector<vector<T>> {
  public:
    using vector<vector<T>>::vector;
};
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/b3bdx53d8

题外话:继承对于您的情况来说是一个糟糕的解决方案。