Вопрос

I'm trying to initialise a jagged array. Why doesn't this work:

int *arr[10];
for (int *row : arr)
    row = new int[10];

it runs but then arr is unreadable.

How can I use this form of "for" properly in this situation?

Otherwise how can I just initialise a jagged array of X rows, each row is Y elements and set all to zero?

Это было полезно?

Решение

Try:

int* arr[10];
for (int*& row : arr)
    row = new int[10];

Since you are changing the value in the array inside of the loop you need to iterate over references instead of values (which are only copies of what was in the array). This is very similar to function call semantics.

Другие советы

for(auto&row:arr)      // note the &. also note the auto
  row = new int[10];

the compilers should really warn about this stupid error. Happened to me many times.

The provided answer by filmor is correct, but as others have already stated in the comments: If you really want to learn C++11 you should use a container like std::vector.

For example:

std::vector<std::vector<int>> list;

And you're done. You can add as many ints as you like. If you want to have a fixed size list of dynamic int-lists, consider using std::array:

std::array<std::vector<int>, 10> arr;

Although I would always recommend using std::vector if performance or memory is not an issue. You have to make sure you're not exceeding the maximum number of elements anyway.

Concerning the for-loop, I would always try to use it this way:

for (auto &item : list)

If you don't want to modify the list, add const:

for (const auto &item : list)

Even if you don't want to modify the list, you're not making copies as you progress through it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top