Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Default argument for vector<int>&?

Tags:

c++

arguments

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

like image 787
voteforpedro Avatar asked Jun 30 '10 07:06

voteforpedro


People also ask

What is the default value of vector?

The default value of a vector is 0.

Are there default arguments in C?

Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.

Does a vector have a default constructor?

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.

Can you use [] for vectors?

As, operator [] returns a reference to the element in vector, so we can change the content of vector too using operator [] i.e.


2 Answers

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); } 
like image 200
ereOn Avatar answered Oct 16 '22 09:10

ereOn


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.

like image 22
sbi Avatar answered Oct 16 '22 07:10

sbi