2
int data[][4] = { {1,2,3,4}, {9,8,7,6}, {2,4,6,8} };

I want to convert this into multidimensional std::array

array< array<int,4>, 3 > stddata = { {1,2,3,4}, {9,8,7,6}, {2,4,6,8} };

like this. But error occur in this code. Why does this error occur? and how can I change reset part { {1,2,3,4}, {9,8,7,6}, {2,4,6,8} } to { , } numbers.

alrnr
  • 41
  • 4

1 Answers1

-3

Update: Here is code using std::array

#include <iostream>
#include <array>

int main() {
    // your code goes here
    std::array< std::array<int, 4>, 3> stddata = {{{1,2,3,4}, {9,8,7,6}, {2,4,6,8}}};
    return 0;
}

If the usecase is to add / remove more values during the lifetime of the container, we can use std::vector. Here is sample code:

#include <iostream>
#include <vector>

int main() {
    // your code goes here
    std::vector< std::vector<int>> stddata = { {1,2,3,4}, {9,8,7,6}, {2,4,6,8} };
    return 0;
}
Mital Vora
  • 2,199
  • 16
  • 19
  • 2
    This should be a comment and not an answer. Data in `array< array, 3 >` is stored continuously in memory. For `std::vector< std::vector>` the data is likely not stored continuously. `std::array` might allow more optimizations, has less memory allocations, … – t.niese Nov 19 '20 at 13:40
  • As per my understanding, `std::vector` is also implemented using underlying array. ref: https://stackoverflow.com/questions/2096571/how-is-c-stdvector-implemented I have also provided the `std::array` implementation for the same with update. – Mital Vora Nov 19 '20 at 13:46
  • why would you prefer `std::vector`? When you give a suggestion like that you need to explain "why" otherwise the suggestion is either useless or leads to cargo cult. I also don't agree btw – 463035818_is_not_an_ai Nov 19 '20 at 13:46
  • 1
    You're using `using namespace std;` that by itself is a thing that should be avoided, but you're also writing `std::` before the declaration of the vectors and arrays. Replace `using namespace std;` with `using std::vector` or `using std::array` and don't write `std::` before them. – Gary Strivin' Nov 19 '20 at 13:48
  • @MitalVora a `std::vector` needs at least two allocations one for `std::vector` itself and one for the data that is stored. `std::array` encloses the data withing the `std::array` type itself. For nested `std:array`s you have only one memory allocation, and continuous memory. So for this example, you have 5 memory allocations for the `std::vector` version and only one for the `std::array` version. – t.niese Nov 19 '20 at 13:49
  • The only reason I prefer using vector is to dynamically add/remove more values to the container. I find it useful. I agree it would have multiple allocations and performance wise, it takes more time for initialization. – Mital Vora Nov 19 '20 at 13:52
  • 2
    @MitalVora if that is your requirement then sure. But if you want to e.g. represent a NxM matrix, you don't want and need to use `std::vector`. – t.niese Nov 19 '20 at 13:53