简体   繁体   中英

How to initialize matrix with 1d vector from nested initialized constructor?

I am facing problem to initialize matrix with a nested form of initializer_lists into a vector member of matrix class. Could you please provide me a solution on how to do it!

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

Something like this?

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

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