npi*_*pit -1 c++ initialization composite stdvector std-pair
我有一个
class myclass
{
// ...
static const vector<pair<string,vector<string>>> var;
// ...
};
Run Code Online (Sandbox Code Playgroud)
在类定义中,使用单个字符串到其他几个字符串的映射.我使用vector <>而不是数组,以便能够添加映射对和映射长度,而不必使用大小变量.有没有办法在相应的.cpp文件中初始化变量,就像非复合类型的向量一样,即格式为:
const vector<pair<string,vector<string>>> myclass :: var =
{
???
}
Run Code Online (Sandbox Code Playgroud)
或者我必须使用静态方法,如
static myclass::initStaticMembers(){...}
Run Code Online (Sandbox Code Playgroud)
如果有第一种方法可以做到这一点,那么语法是什么?我搜索过,但没有找到复合std :: pair初始化的语法.例如,你可以初始化一个vector<string>与
vector <string>myvec={"elem1", "elem2","elem3"};
Run Code Online (Sandbox Code Playgroud)
但你怎么开始复杂的vector<pair<string,vector<string>>>?谢谢.
一如既往地简单 - 只是逻辑地将每个实体与其初始化列表嵌套并使用隐式转换.例如,我已经使用了你的代码并制作了这个例子:
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"}}
};
Run Code Online (Sandbox Code Playgroud)
就在用initiliazer列表编写初始化时,请考虑模板中从左到右的每个实体:
std::vector=需要{ELEM}.结果是{ELEM}.std::vector- 一个std::pair也需要{FIRST, SECOND}.结果是{{FIRST, SECOND}}... 等等.所以,想象它是这样的:
std::vector<std::pair<std::string, std::vector<std::string>>>
^ ^ ^ ^ ^ ^
| | | | | |
{ { "abc" { "abc", "def" } } }
| | | | | |
| | |--------vector-----------| | |
| |--------------------------pair---------------------| |
|---------------------------vector-----------------------------|
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2553 次 |
| 最近记录: |