set模板又称为集合类模板,一个集合对象像链表一样顺序地存储一组值,在一个集合中集合元素既充当存储的数据,又充当数据的关键码。
创建set对象语法如下
std::set<int,std::less<int>>intSet;
下面是部分测试代码 如需自取
#include<iostream> #include<set> #include<map> #include<vector> #include<algorithm> using namespace std; void main(){ set<char>cSet; cSet.insert('B'); cSet.insert('A'); cSet.insert('C'); cSet.insert('D'); cSet.insert('F'); cSet.insert('E'); cout << "old set" << endl; set<char>::iterator it; for (it = cSet.begin(); it != cSet.end(); it++) { cout << *it << endl; } char cTmp; cTmp = 'D'; it = cSet.find(cTmp); cout << "start find" << cTmp << endl; if (it == cSet.end()) cout << "not found" << endl; else cout << "found" << endl; cTmp = 'G'; it = cSet.find(cTmp); cout << "start find" << cTmp << endl; if (it == cSet.end()) cout << "not found" << endl; else cout << "found" << endl; }
集合间的比较
#include<iostream> #include<set> #include<map> #include<vector> #include<algorithm> using namespace std; void main(){ set<char>cSet; cSet.insert('B'); cSet.insert('A'); cSet.insert('C'); cSet.insert('D'); cSet.insert('F'); cSet.insert('E'); cout << "第一个集合:" << endl; set<char>::iterator it; for (it = cSet.begin(); it != cSet.end(); it++) { cout << *it << endl; } set<char>cSet2; cSet2.insert('X'); cSet2.insert('W'); cSet2.insert('R'); cSet2.insert('P'); cSet2.insert('L'); cout << "第二个集合" << endl; for (it = cSet2.begin(); it != cSet2.end(); it++) { cout << *it << endl; } if (cSet == cSet2)//ASCII bijiao cout << "两个集合相等" << endl; else if (cSet < cSet2) cout << "set < set2" << endl; else if (cSet > cSet2) cout << "set>set2" << endl; cout << endl; }