C++集合类模板的解析及使用

拼搏现实的明天。 2023-09-30 15:14 51阅读 0赞

set模板又称为集合类模板,一个集合对象像链表一样顺序地存储一组值,在一个集合中集合元素既充当存储的数据,又充当数据的关键码。

创建set对象语法如下

  1. std::set<int,std::less<int>>intSet;

下面是部分测试代码 如需自取

  1. #include<iostream>
  2. #include<set>
  3. #include<map>
  4. #include<vector>
  5. #include<algorithm>
  6. using namespace std;
  7. void main(){
  8. set<char>cSet;
  9. cSet.insert('B');
  10. cSet.insert('A');
  11. cSet.insert('C');
  12. cSet.insert('D');
  13. cSet.insert('F');
  14. cSet.insert('E');
  15. cout << "old set" << endl;
  16. set<char>::iterator it;
  17. for (it = cSet.begin(); it != cSet.end(); it++)
  18. {
  19. cout << *it << endl;
  20. }
  21. char cTmp;
  22. cTmp = 'D';
  23. it = cSet.find(cTmp);
  24. cout << "start find" << cTmp << endl;
  25. if (it == cSet.end())
  26. cout << "not found" << endl;
  27. else
  28. cout << "found" << endl;
  29. cTmp = 'G';
  30. it = cSet.find(cTmp);
  31. cout << "start find" << cTmp << endl;
  32. if (it == cSet.end())
  33. cout << "not found" << endl;
  34. else cout << "found" << endl;
  35. }

集合间的比较

  1. #include<iostream>
  2. #include<set>
  3. #include<map>
  4. #include<vector>
  5. #include<algorithm>
  6. using namespace std;
  7. void main(){
  8. set<char>cSet;
  9. cSet.insert('B');
  10. cSet.insert('A');
  11. cSet.insert('C');
  12. cSet.insert('D');
  13. cSet.insert('F');
  14. cSet.insert('E');
  15. cout << "第一个集合:" << endl;
  16. set<char>::iterator it;
  17. for (it = cSet.begin(); it != cSet.end(); it++)
  18. {
  19. cout << *it << endl;
  20. }
  21. set<char>cSet2;
  22. cSet2.insert('X');
  23. cSet2.insert('W');
  24. cSet2.insert('R');
  25. cSet2.insert('P');
  26. cSet2.insert('L');
  27. cout << "第二个集合" << endl;
  28. for (it = cSet2.begin(); it != cSet2.end(); it++)
  29. {
  30. cout << *it << endl;
  31. }
  32. if (cSet == cSet2)//ASCII bijiao
  33. cout << "两个集合相等" << endl;
  34. else if (cSet < cSet2)
  35. cout << "set < set2" << endl;
  36. else if (cSet > cSet2)
  37. cout << "set>set2" << endl;
  38. cout << endl;
  39. }

发表评论

表情:
评论列表 (有 0 条评论,51人围观)

还没有评论,来说两句吧...

相关阅读