Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a vector of pair of string,string in a c++ class?

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
like image 305
hitchdiddy Avatar asked Jun 22 '15 17:06

hitchdiddy


People also ask

How do you declare a vector vector of a pair in C++?

A vector of pairs is declared with the expression - vector<pair<int, string>> and it can be initialized the same way as the structure. Once we need to push additional std::pair type elements to the vector , the push_back method can be utilized.

Can we create vector of string?

Each element of a string array contains a 1-by-n sequence of characters. You can create a string using double quotes. As an alternative, you can convert a character vector to a string using the string function. chr is a 1-by-17 character vector.

How do you initialize a pair in C++?

CPP. Initializing a Pair: We can also initialize a pair. Another way to initialize a pair is by using the make_pair() function. g2 = make_pair(1, 'a');


3 Answers

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" }
};
like image 191
Vlad from Moscow Avatar answered Oct 12 '22 23:10

Vlad from Moscow


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{};
like image 38
Cory Kramer Avatar answered Oct 12 '22 21:10

Cory Kramer


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;
like image 3
Rahul Tripathi Avatar answered Oct 12 '22 23:10

Rahul Tripathi