#include <vector>
#include <string>
#include <iostream>
#include <list>
#include <iterator>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <map>
using namespace std;
// map 键值对 自动去重(key) 自动排序(key)
int main()
{
map<char,int> map1;
map1['a']=10;
map1['c']=20;
map1['b']=30;
map<char,int> map2(map1.begin(),map1.end());
map<char,int> map3(map1);
// 遍历
for(pair<char,int> tmp:map1) //自动排序根据 key
cout << tmp.first << "," << tmp.second << endl;
for(auto& x: map1)
cout << x.first << ": " << x.second << '\n';
map<char, int>::iterator it1 = map1.begin();
while(it1 != map1.end())
{
cout << it1->first << "," << it1->second << endl;
it1++;
}
// map的迭代器 也是循环的
it1 = map1.begin();
it1--;
cout << it1->first << "," << it1->second << endl; //,0
it1--;
cout << it1->first << "," << it1->second << endl; //c,20
// 常用操作
// 不改
int m = map1['a'];
cout << m << endl; //10
cout << map1.at('a') << endl; //10
cout << map1.size() << endl;
cout << map1.count('a') << endl; //1 找'a'的个数 在multimap中作用较大
cout << map1.empty() << endl;
cout << map1.max_size() << endl;
it1 = map1.find('a'); //返回迭代器
// 改
map1.swap(map2);
map1.clear();
map1.erase('a'); //按key删
map1.erase(20); //按value删
pair<char, int> p1 = {'d',88};
map1.insert(p1);
map1.emplace(p1);
cout << "equal_range()\n"; //根据key值找 map中 key相等的元素的 起始迭代器和结束迭代器
multimap<char, int> m_map1 = {{'a',1},{'b',2},{'b',5},{'c',3}};
pair<map<char,int>::iterator,map<char,int>::iterator> ret;
ret = m_map1.equal_range('b');
map<char,int>::iterator left = ret.first;
map<char,int>::iterator right = ret.second;
cout << left->second << "," << right->second << endl; // 2,3 [)左开右闭区间
cout << "lower_bound()与upper_bound():\n";
map<char,int>::iterator it3 = m_map1.lower_bound('b'); //找 <='b'的第一个 二分查找,所以数据重复时不一定找到的是想要的
cout << it3->second << endl; //2
multimap<char,int>::iterator it4 = m_map1.lower_bound('b');
cout << it4->second << endl; //2
it3 = m_map1.upper_bound('b'); //找 >'b'的第一个
cout << it3->second << endl; //
cout << "key_comp() \n"; //比较key值是否相等 返回类似函数指针
map<char,int>::key_compare comp = map1.key_comp(); //comp
std::map<char,int>::iterator it = map1.begin();
do {
std::cout << it->first << " => " << it->second << '\n';
}
while ( comp((*it++).first, map1.rbegin()->first)); //comp(key1, key2)
cout << "value_comp() \n"; //比较map中 两个pair<>的value是否相等
bool bool1 = map1.value_comp()(*(map1.begin()), *(map1.begin()));
cout << "emplace_hint() 用参数之间构造对象\n";
cout << "get_allocator() 获取空间配置器 \n";
// unorder_map unorder_multimap 同set
}
c++ STL map的构造及方法
最新推荐文章于 2024-04-04 21:48:02 发布