【发布时间】:2011-03-16 01:47:15
【问题描述】:
如果它真的存在,std::map 扩展初始化列表会是什么样子?
我尝试了一些组合......好吧,我能想到的所有 GCC 4.4 的组合,但都没有找到编译的结果。
【问题讨论】:
标签: c++ c++11 dictionary initializer-list
如果它真的存在,std::map 扩展初始化列表会是什么样子?
我尝试了一些组合......好吧,我能想到的所有 GCC 4.4 的组合,但都没有找到编译的结果。
【问题讨论】:
标签: c++ c++11 dictionary initializer-list
我想在doublep's answer 中补充一点,list initialization 也适用于嵌套地图。例如,如果您有一个 std::map 和 std::map 值,那么您可以通过以下方式对其进行初始化(只要确保您不会被花括号淹没):
int main() {
std::map<int, std::map<std::string, double>> myMap{
{1, {{"a", 1.0}, {"b", 2.0}}}, {3, {{"c", 3.0}, {"d", 4.0}, {"e", 5.0}}}
};
// C++17: Range-based for loops with structured binding.
for (auto const &[k1, v1] : myMap) {
std::cout << k1 << " =>";
for (auto const &[k2, v2] : v1)
std::cout << " " << k2 << "->" << v2;
std::cout << std::endl;
}
return 0;
}
输出:
1 => a->1 b->2
3 => c->3 d->4 e->5
【讨论】:
它存在并且运行良好:
std::map <int, std::string> x
{
std::make_pair (42, "foo"),
std::make_pair (3, "bar")
};
请记住,映射的值类型是pair <const key_type, mapped_type>,因此您基本上需要一个具有相同或可转换类型的对的列表。
通过 std::pair 统一初始化,代码变得更加简单
std::map <int, std::string> x {
{ 42, "foo" },
{ 3, "bar" }
};
【讨论】:
map( std::initializer_list<value_type> init, const Compare& comp = Compare(), const Allocator& alloc = Allocator() );自C++11起可用,而map( std::initializer_list<value_type> init, const Allocator& );仅在自C++11起可用C++14。参考:std::map