'Initialize static array in C++ as a range
I have the following code:
template <int Size>
class A
{
public:
static int size;
static int myArray[Size];
};
The size variable I can set by:
template <int Size>
int A<Size>::size=SomeQuantity;
I would like to initialize the array from 0...Size in steps of 1. E.g, if Size=10, myArray =[0,1,2,....,9]
Can the initialization of a static array be assigned to a function? Is there any C++ built in way of doing this?
Edit I could define inside the class:
static int initArray()
{
for( int i = 0; i<sizeof(myArray)/sizeof(myArray[0]); i++)
{
myArray[i]=i;
}
return 0;
}
And afterwards initialize this as:
template <int Size>
int A<Size>::myArray[Size]={initArray()};
Kind regards
Solution 1:[1]
Write your own function, eg
int* MakeArray(const int size){
int* res = new int[size];
//stl generate transform or just a loop
for (auto i=0;i<size;i++) res[i]=i;
return res;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kaktuts |
