I have a
class myclass
{
// ...
static const vector<pair<string,vector<string>>> var;
// ...
};
in the class definition, to use mappings of single strings to several others. I am using vector<> instead of arrays, in order to be able to add mapping pairs and mapping lengths without having to mantain size variables as well. Is there a way to initialize the variable in the corresponding .cpp file like a vector of a non composite type, that is, in the format:
const vector<pair<string,vector<string>>> myclass :: var =
{
???
}
or do I have to use a static method, like
static myclass::initStaticMembers(){...}
If there is a way to do it in the 1st way, what is the syntax?
I have searched, but did not find the syntax to do the composite std::pair initialization. For example, you can init a vector<string>
with
vector <string>myvec={"elem1", "elem2","elem3"};
but how do you init the complex vector<pair<string,vector<string>>>
?
Thank you.
Simple as always - just logically nest each entity with it's initializer list and with use of implicit conversions. For example, I've worked with your code a bit and made this example:
class A {
static const std::vector<std::pair<std::string, std::vector<std::string>>> var;
};
const std::vector<std::pair<std::string, std::vector<std::string>>> A::var = {
{"abc", {"def", "ghj"}}
};
Just when you write initialization with initiliazer lists think about each entity from left to right in the template:
std::vector
= needs {ELEM}
. Result is {ELEM}
.std::vector
- an std::pair
which also needs {FIRST, SECOND}
. Result is {{FIRST, SECOND}}
.
.. and so on.So, imagine it like this:
std::vector<std::pair<std::string, std::vector<std::string>>>
^ ^ ^ ^ ^ ^
| | | | | |
{ { "abc" { "abc", "def" } } }
| | | | | |
| | |--------vector-----------| | |
| |--------------------------pair---------------------| |
|---------------------------vector-----------------------------|