How to set default value of a vector of int pairs to be empty?

1.2k Views Asked by At

I want to gave a default value (of empty) for a vector of int pairs in a constructor (C++ 98). I've tried things along the following and it (obviously) doesn't work. Could anyone point me in the right direction?

SomeClassName(
const int replace = 1, 
const std::vector<std::pair<int, int> > node = std::vector<std::pair<int, int>() >()
);
2

There are 2 best solutions below

0
On

If you are trying to write a constructor that accepts a vector as input, and you want to make that argument optional, then either:

  1. define two constructors, one that takes a vector and one that doesn't:

    SomeClassName(
        const int replace = 1
    );
    
    SomeClassName(
        const int replace,
        const std::vector<std::pair<int, int> > &node
    );
    
  2. define a single constructor that takes the vector argument with a default-constructed vector as a default value (this is what you are already trying to do, but your syntax is wrong):

    SomeClassName(
        const int replace = 1,
        const std::vector<std::pair<int, int> > &node = std::vector<std::pair<int, int> >()
    );
    
0
On

std::vector<std::pair<int, int>() >() is a value-initialized (empty for std::vector) instance of a vector of functions taking nothing and returning std::pair<int, int>. Simply remove the inner () to get a vector of pairs:

const std::vector<std::pair<int, int> > node = std::vector<std::pair<int, int> >()

You might also want to consider a typedef because there's a lot of noise:

typedef std::vector<std::pair<int, int> > Node;
...
const Node node = Node()