0

The problem

I have an array of int's which vary in value called sizes. I want to create a 2d array (called arr) where the first dimension size is the length of the sizes array, and the second dimension's size is the value of the integer at that index. I hope the following code makes it easier to understand my question.

    int sizes[4] = { 1, 2, 3, 4 };

    // What I need is an array with this shape
    {
        {0},                  // arr[0]
        { 0, 0 },             // arr[1]
        { 0, 0, 0 },          // arr[2]
        { 0, 0, 0, 0 }        // arr[3]
    };

My actual code, the sizes array is larger, so I would like to avoid lots of repeating lines of code if that is possible.

My attempts

I am new to C++, but I have read about constexpr. I think I can create a function to return this array, but I have yet to get this to work.

I also think I can loop over the sizes array, and for each int, create an array with that size, but I can't then assign it to arr.

Kieran
  • 3
  • 1
  • Please use `std::vector` instead of arrays, it's much easier. – cigien Mar 08 '21 at 14:55
  • Thank you for the advice. At the time of writing, I understood that vector indexing was slower than array indexing. It seems that I was wrong, and the performance is equal when indexing a pointer object. – Kieran Mar 09 '21 at 16:57

1 Answers1

3

C++ doesn't support jagged 2d arrays. A 2d array needs to have a size of N x M where N and M are both greater than zero.

Instead of using a 2d array, you can use a 2d vector to get this behavior like

std::vector<std::vector<int>> table;
for (auto size : sizes)
    table.push_back(std::vector<int>(size));
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Thank you for the reply. I did think of using vectors however, and correct me if I am wrong, but isn't indexing from an array quicker than from a vector? I need to squeeze as much performance out of my code as I can. – Kieran Mar 08 '21 at 15:49
  • @Kieran With compiler optimizations turned on, accessing a vector and accessing an array should have the same performance. – NathanOliver Mar 08 '21 at 15:52
  • Thank you, I did not know that. I will research more into it then. – Kieran Mar 08 '21 at 16:24
  • @Kieran Some intro reading: https://stackoverflow.com/questions/2740020/c-stl-array-vs-vector-raw-element-accessing-performance – NathanOliver Mar 08 '21 at 16:26