I was just wondering, if I am setting up a vector to be a prototype of a function how do I define this? I know that I have the option of using dynamic memory allocation, but I was wondering if instead I could just use:
void Function(double vector[]) { }
and in the main bit of code, allocate it some entries?
Is this an acceptable method?
CodePudding user response:
Firstly, you should not use vector
as it is part of the standard library (std::vector
).
If the vector you describe has always the same dimension, you can create a structure:
struct Vector3D
{
double x = 0.0;
double y = 0.0;
double z = 0.0;
};
And then use it in your function and main:
void Function(Vector3D v) { }
int main()
{
Vector3D v = {1.0, 0.0, 0.0}; // Unit X
Function(v);
return 0;
}
CodePudding user response:
Do this
template<class T>
void Function(std::vector<T>& vector)
{
// do your thing
}
For arrays you can also do
template<int N>
void Function(std::array& array)
{
// do your thing
}