Basically I'd like to do something like that:
int[3] array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
int[3] point=array_func();
}
But that doesn't seem legal in C++. I know I can use vectors, but since I know the size of the array is a constant, it seems like a loss of performance is likely to occur.
I'd also like to avoid a new
if I can, because allocating stuff on the stack is easier and also likely to improve performance.
What's the solution here?
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
The first one would be called like func1(foo, foo + CAPACITY) : passing in a pointer to the start of the array, and a pointer to just beyond the last element. The second would be called like func2(foo, CAPACITY) : passing in a pointer to the start of the array and the array size.
Because fixed arrays have memory allocated at compile time, that introduces two limitations: Fixed arrays cannot have a length based on either user input or some other value calculated at runtime. Fixed arrays have a fixed length that can not be changed.
Passing the array size tells the function where the bounds are so you can choose not to go beyond them. This is inherited from C language, if you use std::array or std::vector you don't need to use array size as a parameter function.
Using C++0x, the almost finalized new C++ standard (already implemented in latest gcc and msvc IIRC), you can do it exactly as you want! Simply use std::array instead of int[3].
std::array<int, 3> array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
std::array<int, 3> point = array_func();
}
Put the array into a struct. boost::array
is such a package:
boost::array<int, 3> array_func() {
boost::array<int, 3> a = {{ 1, 1, 1 }};
return a;
}
int main() {
boost::array<int, 3> b = array_func();
}
Quick and dirty:
template<typename E, size_t S>
struct my_array {
E data[S];
};
Notice how you can use aggregate initialization syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With