+ 2
Array in C++
hi guys, i have to do a function which returns an array of 0 and 1, which order depends on the parameter passed to the function; for example using js i would have done something like this: function f(n){ var stmap; switch(n){ case 0: stmap=[1,1,1,1,1,1,0]; break; case 1: stmap=[0,1,1,0,0,0,0]; break; ...ecc } return stmap; } using C++, i do: case0: stmap[0]=1; stmap[1]=1; ..ecc is there a faster method?
2 Answers
+ 3
You can use an initializer_list for this.
http://en.cppreference.com/w/cpp/utility/initializer_list
like: int arr[4] = {0,1,1,0};
If for some reason you can't initialize it immediatly after declaring you can make your own function.
template<typename T>
void copyPattern( T* arr, const std::initializer_list<T>& il )
{
std::size_t index = 0;
for( const auto& i : il )
arr[index++] = i;
}
then you can call it like:
int arr[10];
// Skipping init
copyPattern( arr, {1,1,0,1} );
Fills in arr[0] through arr[3] with the pattern.
copyPattern( arr + 5, {1,1,0,1} );
Fills in arr[5] through arr[8] with the pattern.
Note that the function does not do any out-of-bounds checking.
Also note that C++ cannot return arrays from functions.
It can return pointers that point to the start of an array though but then you'll have to play with new/delete.
Might want to look at std::vectors.
http://en.cppreference.com/w/cpp/container/vector
0
thank you @Dennis
i have never seen this code, i don't understand it at all, i have to deepen it a bit more, but it seems good ;)