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;
}