0

I'd like to change the construction of std::array<unsigned int, size> the following way:

  • myarray a {}; should construct [0,1,2,3,4...] instead of [0,0,0,0,...]
  • myarray a {5,2}; should construct [5,2,2,3,4...] instead of [5,2,0,0,0...]

One obvious solution is to have a class:

template <size_t size>
struct myarray {
    std::array<int, size> ar;
    myarray() { for (size_t i=0; i<size; i++) ar[i]=i; }
    myarray(std::initializer_list<unsigned int> il) :ar(il) {
        for (size_t i=il.size(); i<size; i++) ar[i]=i; 
    } 
    ...
};

However it forces me to wrap every single member of ar. As far as I understand, inheriting from std::array is not a very good idea. Is there a third reasonable way ?

hivert
  • 10,579
  • 3
  • 31
  • 56
  • 1
    `my_make_array(std::initializer_list)` ? – Jarod42 Mar 28 '14 at 08:04
  • @Jarod42 : Are you suggesting some kind of factory function ? Then how do you ensure that the array is always constructed trough this function ? I don't want a user to call the usual constructor inadvertently. – hivert Mar 28 '14 at 08:08
  • Yes I suggested a factory function. But it seems that it doesn't fit your needs. – Jarod42 Mar 28 '14 at 08:24

2 Answers2

0

It would be a very bad idea to change it globally. For all you know, std::cout internally uses a std::array. Even in your own code, the principle of least surprise dictates that std::array<int, 5> creates [0,0,0,0,0]. That's the whole point of std:: - "STandarD".

So, the proper solution is to use a function which returns an array constructed like you want.

BTW, you can replace the for-loop with a single call to std::iota(begin(ar)+il.size(), end(ar), il.size())

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

I believe my earlier post on the similar topic would be useful.

https://stackoverflow.com/a/21651027/2724703

Community
  • 1
  • 1
Mantosh Kumar
  • 5,659
  • 3
  • 24
  • 48