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

August 11th, 2009 § 1 Comment

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

§ One Response to Difference between “vector v” and “vector v()”

  • Or says:

    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

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading Difference between “vector v” and “vector v()” at 0x.

meta