STL之set、map基本使用例項
阿新 • • 發佈:2019-01-23
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;
}