map类
map基本操作和使用:
map是STL的一个关联容器,提供一对一的数据处理能力,底层是一棵红黑树,并且有自动排序功能。map可以修改值,但不能修改key。key和vaule可以是任意你需要的类型,map查找元素的复杂度大概是O(log n)
map构造:
例如:map<int, string> mapint;
map的插入数据:
1、pair函数插入:
tmp_map.insert(pair<int,string>(1,"abc"));
2、value_type插入:
tmp_map.insert(map<int,string>::value_type(1,"abc"));
3、直接插入:
tmp_map[1] = "abc";
(注:如果tmp_map[2]没有value,则默认为空字符串)
map的查找:
用find函数,如果没有找到就返回tmp_map.end()
示例代码:
1 #include <iostream> 2 #include <map> 3 using namespace std; 4 int main() 5 { 6 map<int, string> m; 7 m[1] = "abc"; 8 m[2] = "def"; 9 map<int, string>::iterator l; // 定义一个迭代器 10 l = m.find(1); 11 if(l != m.end()) cout << "Find it 1" << endl; 12 else cout << "Not find 1" << endl; 13 l = m.find(3); 14 if(l != m.end()) cout << "Find it 3" << endl; 15 else cout << "Not find 3" << endl; 16 return 0; 17 }
map元素删除:
用erase函数
示例代码:
1 #include <iostream> 2 #include <map> 3 using namespace std; 4 int main() 5 { 6 map<int, string> m; 7 m[1] = "abc"; 8 m[2] = "def"; 9 map<int, string>::iterator l; 10 l = m.find(1); 11 if(l == m.end()) cout << "Not find" << endl; // 查看是否存在该元素 12 else m.erase(1); 13 l = m.find(1); 14 if(l == m.end()) cout << "Not find 2" << endl; // 检查是否删除 15 return 0; 16 }
map容器元素交换:
用swap,是两个容器的交换。
常用操作函数:
map.begin() 返回头部迭代器
map.clear() 删除所有元素
map.count() 返回指定元素出现次数
map.empty() 判空,空位true
map.end() 返回尾部迭代器
map.erase() 删除一个元素
map.find() 查找
map.max_size() 可容纳最大元素个数
map.size() 返回map中元素个数
map不能用sort排序
map的遍历:
示例代码:
1 #include <iostream> 2 #include <map> 3 using namespace std; 4 int main() 5 { 6 map<int, string> m; 7 m[1] = "abc"; 8 m[2] = "def"; 9 map<int, string>::iterator l; 10 for(l = m.begin(); l != m.end(); l++) 11 cout << l->first << " " << l->second << endl; // first是key second是value 12 return 0; 13 }

浙公网安备 33010602011771号