简体   繁体   中英

create a Dynamic std::array of std::array

My task requires me to create an array of arrays to store some data , where the number of row is fixed and the columns are to be decided at run-time.

If I was using a simple int array then this would've been a simple task but because I have to use std::array , I am lost .

My attempt so far

#include<iostream>
#include<array>
using std::array;
int main(){
  array<array<int,1>*,3> x;
  for(size_t i=0;i<3;i++)
      {
        x[i][0]=array<int,3>;
      }
}

which leads to the error

array1.cpp:12:29: error: expected '(' for function-style cast or type construction x[i][0]=array; ~~~~~~~~~~~~^ 1 error generated.

when using clang++

I have read that an std::array is equivalent to a normal array , I know i can use vectors but since i know how many rows i have from the beginning , I feel it to be a waste to use vectors , while I would love the added functionality of std::array when compared to a traditional array. How do I implement this .

std::array<std::vector<int>,3> is the type you want.

std::vector is a dynamicly sized array.

int main(){
  std::array<std::vector<int>,3> x;
  for(std::size_t i=0;i<3;i++)
  {
    x[i]=std::vector<int>(22);
  }
}

this creates a 3 "major" element array of 22 "minor" size.

Note that column-major and row-major (which is first and which is second) is a matter of convention. So std::vector<std::array<3,int>> is another equally valid interpretation of the requirements.

If you are banned from using std::vector , you will have to figure out an alternative solution, possibly rolling your own. I'd advise against unique_ptr<int[]> (or worse, raw pointers) as they don't store the size of the element.

A std::array< std::array< cannnot be dynamic in either dimension. std::array is fixed size.

My task requires me to create an array of arrays to store some data , where the number of row is fixed and the columns are to be decided at run-time.

It sounds like your task requires using a matrix class. Like boost::numeric::ublas::matrix .

The benefit of using a matrix class is that internally it uses one dynamic array to minimize storage overhead.

If you are coding this as an exercise create your own matrix class. Otherwise use an existing one.

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