C++11的初始化列表:如何快速填充关联容器?
·
在C++11中,初始化列表为关联容器(如std::map、std::set)提供了简洁高效的填充方式。以下是具体方法和示例:
1. 直接初始化填充
通过花括号{}在构造时直接填充元素:
// 初始化set
std::set<int> numSet = {3, 1, 4, 1, 5}; // 自动排序去重:{1, 3, 4, 5}
// 初始化map
std::map<std::string, int> scoreMap = {
{"Alice", 90},
{"Bob", 85},
{"Charlie", 92} // 键值对列表
};
2. 构造后批量插入
使用insert()的重载版本接受初始化列表:
std::set<std::string> colors;
colors.insert({"red", "green", "blue"}); // 批量插入元素
std::map<int, std::string> idMap;
idMap.insert({{101, "John"}, {102, "Jane"}}); // 批量插入键值对
3. 嵌套容器初始化
对值类型为容器的关联容器(如map套vector):
std::map<int, std::vector<int>> matrix = {
{1, {2, 4, 6}},
{2, {1, 3, 5}},
{3, {0, 9, 7}}
};
4. 自定义类型支持
若键或值为自定义类型,需确保支持比较操作:
struct Point { int x, y; };
auto comp = [](const Point& a, const Point& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
};
std::set<Point, decltype(comp)> pointSet(comp);
pointSet.insert({{1,2}, {3,4}, {1,2}}); // 插入时自动去重
优势分析
- 高效性:一次性插入避免多次树平衡/哈希重组
- 可读性:代码直观简洁,减少冗余操作
- 安全性:编译时检查类型和初始化合法性
⚠️ 注意:
std::map的键必须唯一,重复键会导致后值覆盖前值;std::multimap则允许多个相同键值。
更多推荐
所有评论(0)