Reputation: 15
I want to know how to intialize values to some elements of array such as.
int arr[5]={3,5,6};
in a way that the index of 3 is 0 and 5 is 2.
So index 1 is skipped and automatically assigned value by compiler!
Thanks for the help!
Upvotes: 1
Views: 4073
Reputation: 238311
I want to know how to intialize values to some elements of array ... So index 1 is skipped
This is not possible. It is only possible to provide an initaliser to elements in order; they cannot be skipped. What you can do is initialise the array to zero, and assign some of the elements later. Example:
int arr[5]{};
arr[0] = 3;
arr[2] = 5;
or, you can use default initialisation instead:
int arr[5];
arr[0] = 3;
arr[2] = 5;
In which case the elements will have indeterminate values until assigned. Do not ever read indeterminate values; It is not useful and typically results in undefined behaviour.
Upvotes: 1
Reputation: 122133
in a way that the index of 3 is 0 and 5 is 2.
That would be
int arr[5] = {3,0,5,6};
So index 1 is skipped and automatically assigned value by compiler!
You cannot skip elements in the middle, only in the end as in your
int arr[5] = {3,5,6};
Where the missing elements in the end are initialized with 0.
Note that what you want is possible in C. Example from cppreference:
int n[5] = {[4]=5,[0]=1,2,3,4} // holds 1,2,3,4,5
However this is not (yet?) possible in standard C++.
PS: If you do not care about portability (actually you should) you can study your compilers manual to see if it allows the c-style initialization also in C++.
Upvotes: 5