I'm having a scenario where I need to add a vector as an input/output [reference]parameter to existing legacy code. And in order to avoid any errors, I need to make it a default parameter.
Could someone please suggest how to add a vector as a default parameter to a method. I'm actually dubious if this is possible. Also, if this is possible, with what vallue should the vector be intialized with?
We can also specify a random default value for the vector. In order to do so, below is the approach: Syntax: // For declaring vector v(size, default_value); // For Vector with a specific default value // here 5 is the size of the vector // and 10 is the default value vector v1(5, 10);
You can use: std::vector<int> v(100); // 100 is the number of elements. // The elements are initialized with zero values.
I suggest overloading the method:
void foo(double otherParameter);
void foo(double otherParameter, std::vector<int>& vector);
inline void foo(double otherParameter)
{
std::vector<int> dummy;
foo(otherParameter, dummy);
}
An alternative design, which explicitly says that vector
is an option in/out parameter, is:
void foo(double parameter, std::vector<int>* vector = 0);
Yes, a raw pointer -- we're not taking ownership of it, so smart pointers are not really needed.
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