cplusplus.co.il

Difference between “vector v” and “vector v()”

Posted on: 11/08/2009

The given two statements actually translate to two very different declerations.

Is there a difference between the two options, in the following piece of code?

#include <vector>
using std::vector;

int main () {
    vector<int> v1;  // option 1
    vector<int> v2(); // option 2
}

Hint: v2 isn’t really a vector (try calling a method).

Advertisements

1 Response to "Difference between “vector v” and “vector v()”"

Yes, it’s called The Most Vexing Parse, and it is a really vexing one. When you say vector v2() you are actually importing an external function(named v2 and that returns a vector of ints and has no parameters) from another translation unit.
This can be even more vexing if you write:
Suppose you want to read a file which his name stored in a variable filename, and copy it directly into a new vector:

vector<int> v(istream_iterator<int>(filename), istream_iterator<int>());

Although it is somehow not trivial example, that will be parsed by the vexing c++ compiler as a function declaration (because the parenthesis can be omitted to get a function declaration), not a vector initialization. to remedy the situation we have to do something like the following:

istream_iterator<int> begin(filename);
istream_iterator<int> end;
vector<int> v(begin, end).

Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: