I have a function,
void test( vector<int>& vec );
How can I set the default argument for vec ? I have tried
void test( vector<int>& vec = vector<int>() );
But there's a warning "nonstandard extension used : 'default argument' : conversion from 'std::vector<_Ty>' to 'std::vector<_Ty> &'"
Is there a better way to do this ? Instead of
void test() { vector<int> dummy; test( dummy ); }
Regards, Voteforpedro
The default value of a vector is 0.
Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.
The default vector constructor takes no arguments, creates a new instance of that vector. The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c. All of these constructors run in linear time except the first, which runs in constant time.
As, operator [] returns a reference to the element in vector, so we can change the content of vector too using operator [] i.e.
Have you tried:
void test(const vector<int>& vec = vector<int>());
C++
does not allow temporaries to be bound to non-const references.
If you really to need to have a vector<int>&
(not a const
one), you can declare a static instance and use it as a default (thus non-temporary) value.
static vector<int> DEFAULT_VECTOR; void test(vector<int>& vec = DEFAULT_VECTOR);
But beware, because DEFAULT_VECTOR will (can) be modified and won't reset on each call ! Not sure that this is what you really want.
Thanks to stinky472, here is a thread-safe alternative:
Instead of providing a default value, you might as well overload test()
with a zero-parameter version which calls the other version:
void test() { vector<int> vec; test(vec); }
I find it questionable for a non-const
reference argument to have a default value. What is this supposed to mean?
Commonly, a function taking a non-const
reference means "I might change the argument". If the argument is optional why no pass a (non-const
) pointer? That way, when callers don't want to pass an arguments, they can pass NULL
.
(See here for more information on how to pass function arguments.)
Edit: Well, and of course, there's also overloading. Just add another overload which doesn't take this argument.
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