16

For example, a class named Table, with its constructor being: Table(string name="", vector <string> mods);

How would I initialize the vector to be empty?

Edit: Forgot to mention this was C++.

d-_-b
  • 6,555
  • 5
  • 40
  • 58
Omar
  • 750
  • 3
  • 7
  • 13

2 Answers2

25
Table(string name="", vector <string> mods);

if you want vector to be empty inside constructor then

mods.clear();

or

mods.swap(vector<string>());

In case you want as a default parameter:

 Table(string name="", vector<string> mods = vector<string>());

Like any other default parameter.

aJ.
  • 34,624
  • 22
  • 86
  • 128
  • Ahh thanks! I kept trying things like vector mods(0,"") and many other variations. Wouldn't have guessed this at all! – Omar Dec 06 '09 at 03:31
  • Caught your message before you edited it, this method works vector mods = vector() and just vector mods = vector() complains about needing a template argument. I'm glad I saw the first message because I probably wouldn't have figured out to put the template argument in both sides of the assignment. – Omar Dec 06 '09 at 03:38
  • If by any chance you want your argument `vector mods` to be of `reference` then you must use `const` in such cases, because `C++` doesn't allow temporary variables to be associated with the `reference`. – Krishna Oza Mar 09 '16 at 12:04
10

To add to the other answer: If you're using c++11, you can use the universal initialization syntax to shorten the default parameter declaration for a vector to the following:

Table(string name="", vector<string> mods={});
user35147863
  • 2,525
  • 2
  • 23
  • 25