Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default for a vector in a method

Tags:

c++

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?

like image 370
Pavan Dittakavi Avatar asked Aug 04 '11 14:08

Pavan Dittakavi


People also ask

How do you create a default value for a vector?

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);

How do you initialize a vector with all values 0?

You can use: std::vector<int> v(100); // 100 is the number of elements. // The elements are initialized with zero values.


1 Answers

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.

like image 111
quant_dev Avatar answered Oct 18 '22 15:10

quant_dev