C++map的初始化

map的初始化有两种方式:

1、直接赋值

       map[key]=value;

2、用insert添加pair类型的元素

#include<map>
#include<string>
#include<iostream>

using namespace::std;

int main()
{
	//直接赋值法
	map<string, int> m1;
	m1[string("abc")] = 1;
	m1[string("defg")] = 2;

	//用insert添加
	map<string, int> m2;
	m2.insert({ string("abc"), 1 });
	m2.insert(make_pair(string("defg"), 2));
	m2.insert(pair<string, int>(string("hijk"), 3));

	//打印 m1,m2
	auto it1 = m1.begin();
	cout << "m1:" << endl;
	while (it1 != m1.end())
	{
		cout << it1->first << " " << it1->second << endl;
		it1++;
	}
	cout <<"m2:" << endl;
	auto it2 = m2.begin();
	while (it2 != m2.end())
	{
		cout << it2->first << " " << it2->second << endl;
		it2++;
	}
	system("pause");
	return 0;
}


### C++map初始化方法及示例 在 C++ 中,`std::map` 是一种关联容器,用于存储键值对,并根据键进行排序。以下详细介绍 `std::map` 的初始化方法及示例代码。 #### 1. 使用直接初始化方式 可以直接通过构造函数初始化一个空的 `std::map`,或者使用键值对列表初始化一个非空的 `std::map`[^1]。 ```cpp #include <map> #include <string> std::map<int, std::string> myMap = { {1, "one"}, {2, "two"}, {3, "three"} }; ``` 上述代码中,`myMap` 被初始化为包含三个键值对的 `std::map`。 #### 2. 使用拷贝初始化方式 可以通过拷贝另一个 `std::map` 来初始化一个新的 `std::map`[^1]。 ```cpp std::map<int, std::string> anotherMap = myMap; ``` 这里,`anotherMap` 是通过拷贝 `myMap` 初始化的。 #### 3. 使用统一初始化C++11 及以上) 从 C++11 开始,可以使用花括号 `{}` 进行统一初始化[^2]。这种方式不仅简洁,而且避免了某些情况下传统的圆括号 `()` 初始化可能引发的歧义。 ```cpp std::map<int, double> valueMap{{1, 3.14}, {2, 2.718}, {3, 1.618}}; ``` #### 4. 初始化为空的 map 如果需要初始化一个空的 `std::map`,可以简单地使用默认构造函数。 ```cpp std::map<std::string, int> emptyMap; ``` #### 5. unordered_map初始化(可选) 虽然问题主要关注 `std::map`,但为了完整性,也简要介绍 `std::unordered_map` 的初始化方式。`std::unordered_map` 是基于哈希表实现的关联容器,其初始化方式与 `std::map` 类似,但不需要按键排序[^3]。 ```cpp #include <unordered_map> #include <string> std::unordered_map<std::string, int> people = { {"Alice", 30}, {"Bob", 25}, {"Charlie", 35} }; ``` 还可以通过自定义哈希函数来初始化 `std::unordered_map`[^4]。 ```cpp struct Hash_Name { size_t operator()(const std::pair<std::string, std::string>& name) const { return std::hash<std::string>()(name.first) ^ std::hash<std::string>()(name.second); } }; std::unordered_map<std::pair<std::string, std::string>, int, Hash_Name> customMap{ {{"Ann", "Ounce"}, 25}, {{"Bill", "Bao"}, 46}, {{"Jack", "Sprat"}, 77} }; ``` ### 注意事项 - 在使用花括号 `{}` 初始化时,确保键值对格式正确,否则可能会导致编译错误或运行时异常。 - 如果键类型是自定义类型,则需要确保该类型支持 `<` 操作符重载(对于 `std::map`),或者提供适当的哈希函数和比较函数(对于 `std::unordered_map`)。 ---
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值