如何使用嵌套初始化构造函数中的1d向量初始化矩阵?

时间:2019-06-20 22:36:52

标签: c++ c++11 stdvector

我面临将嵌套形式的initializer_lists初始化为矩阵类的向量成员的问题。您能为我提供解决方法吗?

   #include <initializer_list>
   #include <iostream>
   #include <stdexcept>
   #include <vector>
   using namespace std;
   class matrix {
   private:
   unsigned int rows;
   unsigned int columns;
   vector<int> data;
   public:{
   matrix(size_t rows, size_t columns):rows(0),columns(0),data(){
};
   matrix(size_t ros, size_t cols, const int &ival){
    data.clear();
    rows =ros;
    columns = cols;
     size_t vSize = rows*columns; 
    for(unsigned int i = 0; i < vSize; i++) {
    data.push_back(ival);
     } 
   };
   friend ostream &operator<<(ostream &os, const matrix &m){
   for(size_t i = 0; i < m.data.size(); i++) {
    os << m.data[i] << "  ";
    if((i+1)%m.num_columns() == 0) 
        os <<"\n";
     }
     return os;
    };
   matrix(initializer_list<initializer_list<int>> imat); //require 
   //implementation of constructor to feed nested initializer list data in 
   //1d vector data

  }

  int main() {   
   matrix<double> d = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   cout<<d;
   return 0;
  }

1 个答案:

答案 0 :(得分:1)

像这样吗?

matrix(std::initializer_list< std::initializer_list< int > > imat)
    {
        for (auto &row : imat)
        {
            data.insert(data.end(), row.begin(), row.end());
        }
    }