STL之set、map基本使用实例

来源:互联网 发布:买假条 淘宝怎么搜索 编辑:程序博客网 时间:2024/05/16 09:05

set和map都是关联式容器,二者都对内部元素默认排序:升序。

set是key结构 , map是key-value结构;

set可以去重 , map重载了[ ],查询速度快;


set包含的基本方法:


map的基本方法



使用这些函数的实例

void test_set(){//set是 key结构的,是关联式容器,对插入的元素自动排序,默认是升序set<int> Myset;set<int> ::iterator it;cout << "insert() , size() , begin() , end() " << endl;Myset.insert(5);Myset.insert(3);Myset.insert(1);Myset.insert(7);cout << Myset.size() << endl;cout << Myset.max_size() << endl;for (it = Myset.begin(); it != Myset.end(); ++it){cout << "   " << *it;}cout << endl;cout << " find(),  erase() ,  clear()   , empty() 测试:" << endl;it = Myset.find(5);Myset.erase(it, Myset.end());   //删除Myset的it到end之间的元素for (it = Myset.begin(); it != Myset.end(); ++it){cout << "   " << *it;}cout << endl;cout << Myset.empty() << endl;}


void test_map(){map<string, int> Mymap;cout << "insert()  , begin() , clear( ) 测试:" << endl;Mymap.insert(pair<string ,int>("vector", 1));  //插入 key-value Mymap.insert(pair<string ,int>("map", 4));Mymap.insert(pair<string ,int>("set", 3));Mymap.insert(pair<string ,int>("list", 2));map<string, int>::const_iterator  it;for (it = Mymap.begin(); it != Mymap.end(); ++it){cout << it->first << "~~" << it->second<< endl;  //!!!这里编译不通过,肯定是你没有包含string头文件!}cout << "[] , find() ,  count(), clear() , size() , empty() " << endl;cout << Mymap["map"] << endl;it = Mymap.find("list");  //find() 查找一个元素cout << (*it).first << " : " << (*it).second<< endl;cout << Mymap.count("map") << endl;//count() 返回指定元素出现的次数cout << Mymap.size() << endl;Mymap.clear();cout<< Mymap.empty() << endl;}


0 0
原创粉丝点击