版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013919153/article/details/82460176
#define VNAME(value) {cout<<(#value)<<":"<<endl;}
template<class T>
void print_map(T &v)
{
for (auto tmp : v)
{
cout<<"key:"<<tmp.first<<" value:"<<tmp.second<<endl;
}
}
/**
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<Key>, // map::key_compare
class Alloc = allocator<pair<const Key,T> > // map::allocator_type
> class map;
**/
/**
**map与set的区别就是:set是map的特例,即key和value相同
**故set的成员函数和map类似
**multimap与map的区别为:multimap有序,可以存相同key的value_type
**/
void test_map(){
map<int,string> a;
a[1] = "test";
a[2] = "big";
a[3] = "small";
a[4] = "middle";
map<int,string,classcomp> c;
c[5] = "five";
c[6] = "six"; //可以通过key赋值,也可以通过key访问value
c[7] = "seven";
/**
迭代器:begin,end,rbegin,rend及对应的const
map的迭代器不能与整数进行加操作,因为内存不是连续的,底层实现红黑树
**/
cout<<"size of a :" <<a.size()<<endl;
cout<<"max_size of a :"<<a.max_size()<<endl;
cout<<"key:2 -- value:"<<a[2]<<endl;
//cout<"key:3 -- value:"<<a.at(3)<<endl; //c++11有些编译器没有完全支持
//返回pair<iterator,bool>
a.insert(c.begin(),c.find(6)); //1,2,3,4,5
a.insert(map<int,string>::value_type(8,"eight"));
a.insert(a.find(3),pair<int,string>(9,"nine")); //因为有序,所以插入位置不怎么管用
a.emplace(10,"ten");
a.emplace_hint(a.end(),11,"eleven");
VNAME(a)
print_map(a);
a.erase(a.find(2),a.find(4)); //返回被删除元素的下一个存在元素的迭代器
a.erase(1); //因为有序唯一,所以返回size_t为0或者1
a.erase(a.begin());
VNAME(a)
print_map(a);
//a.swap(c); //交换内容,这里错误,a和c不是相同类型
//key_comp(); //获取key比较函数,即模板第三个参数
// value_comp(); //返回一个value比较函数,区别于key比较函数
cout<<"key num of 2 in a is "<<a.count(2)<<endl;
//multimap中使用获取一个范围
auto i = a.lower_bound(3); //若key不存在返回第一个元素迭代器
auto j = a.upper_bound(8); //存在返回下一个元素的迭代器;不存在,返回第二个元素的迭代器
auto k = a.equal_range(3);
c.clear(); //清空c中数据
if (c.empty())
{
cout<<"c is empty"<<endl;
}
//multimap ,相对于map来说,可以存储多个相同key相同的值
cout<<endl<<endl;
}