Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill in the int array from zero to defined number

Tags:

c++

arrays

i need to fill in the int[] array in C++ from zero to number defined by variable, but ISO C++ forbids variable length array... How to easily fill in the array? Do i need to allocate/free the memory?

int possibilities[SIZE];
unsigned int i = 0;
for (i = 0; i < SIZE; i++) {
    possibilities[i] = i;
}

btw. if you would ask - Yes, i need exactly standard int[] arrays, no vectors, no maps etc.

like image 388
Radek Simko Avatar asked Jan 26 '11 11:01

Radek Simko


1 Answers

In c++11 you can use std::iota and std::array. Example below fills array sized 10 with values from 1 to 10.

std::array<int, 10> a;
std::iota(a.begin(), a.end(), 1);

Edit Naturally std::iota works with vectors as well.

like image 183
jarno Avatar answered Oct 03 '22 15:10

jarno