以下静态初始值设定项列表M失败,但N成功,当将3 const char *指针的并集添加到init-list时,似乎我不知道如何进行unordered_map初始化。我尝试了。表示无法访问联合字段和联合本身的符号。
#include <iostream>
#include <unordered_map>
#include <iterator>
struct C {
int j;
int i;
};
struct D {
int j;
char c;
};
struct E {
const char *a;
const char *b;
const char *c;
}e;
struct A {
const char *s;
union {
C c;
D d;
E e;
} u;
};
std::unordered_map<unsigned int, A> m ({
{1, {"tom",53,'o'}},
{2, {"ming",40,41}},
{3, {"peter","a","b","c"}} });
std::unordered_map<unsigned int, A> n ({
{1, {"tom",53,'o'}},
{2, {"ming",40,41}} });,
int main(void) {
for ( const auto& i : m) {
const auto& j = i.second;
if (i.first == 1)
std::cout << "key: " << i.first << " value: " << j.u.d.j << ":" << j.s << ":" << j.u.d.c << std::endl;
else if (i.first == 2)
std::cout << "key: " << i.first << " value: " << j.u.c.j << ":" << j.s << ":" << j.u.c.i << std::endl;
else if (i.first == 3)
std::cout << "key: " << i.first << " value: " << j.u.e.a << ":" << j.s << ":" << j.u.e.c << std::endl;
}
for ( const auto& i : n) {
const auto& j = i.second;
if (i.first == 1)
std::cout << "key: " << i.first << " value: " << j.u.d.j << ":" << j.s << ":" << j.u.d.c << std::endl;
else if (i.first == 2)
std::cout << "key: " << i.first << " value: " << j.u.c.j << ":" << j.s << ":" << j.u.c.i << std::endl;
}
return 0;
}
错误: map.cpp:41:32:错误:没有匹配的函数可以调用“ std :: unordered_map :: unordered_map()”