Reputation: 129
How do I initialize a vector of a pair of strings in a C++ class? I tried several things but none worked out.
vector<pair<string,string>> myVec(); //doesn't work
Upvotes: 7
Views: 13555
Reputation: 310940
There is no need to initialize a vector such a way
vector<pair<string,string>> myVec();
It is a function declaration with name myVec
that does not have parameters and has return type vector<pair<string,string>>
It is enough to write simply
vector<pair<string,string>> myVec;
because in any case you are creating an empty vector.
Or if you want that the vector had some initial values and your compiler supports C++ 2011 then you can also write for example
std::vector<std::pair<std::string, std::string>> myVec =
{
{ "first", "first" }, { "second", "second" }, { "third", "third" }
};
Upvotes: 13
Reputation: 172398
Try to use it like this, presently your function myVec
has no parameters and return vector<pair<string,string>>
:
vector<pair<string,string>> myVec{};
or
vector<pair<string,string>> myVec;
Upvotes: 3
Reputation: 117856
If you use ()
you run into the most vexing parse. You declared a function myVec
that takes no arguments, and returns a vector<pair<string, string>>
Switch to {}
vector<pair<string,string>> myVec{};
Upvotes: 9