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

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

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



相关文章
|
4天前
|
设计模式 安全 算法
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
15 0
|
3天前
|
编译器 C++
【C++】继续学习 string类 吧
首先不得不说的是由于历史原因,string的接口多达130多个,简直冗杂… 所以学习过程中,我们只需要选取常用的,好用的来进行使用即可(有种垃圾堆里翻美食的感觉)
7 1
|
3天前
|
算法 安全 程序员
【C++】STL学习之旅——初识STL,认识string类
现在我正式开始学习STL,这让我期待好久了,一想到不用手撕链表,手搓堆栈,心里非常爽
10 0
|
3天前
|
存储 安全 测试技术
【C++】string学习 — 手搓string类项目
C++ 的 string 类是 C++ 标准库中提供的一个用于处理字符串的类。它在 C++ 的历史中扮演了重要的角色,为字符串处理提供了更加方便、高效的方法。
12 0
【C++】string学习 — 手搓string类项目
|
3天前
|
存储 算法 编译器
C++的模板与泛型编程探秘
C++的模板与泛型编程探秘
9 0
|
3天前
|
编译器 C++
【C++从练气到飞升】08---模板
【C++从练气到飞升】08---模板
|
3天前
|
Java C++ Python
【C++从练气到飞升】06---重识类和对象(二)
【C++从练气到飞升】06---重识类和对象(二)
|
3天前
|
编译器 C++
【C++从练气到飞升】06---重识类和对象(一)
【C++从练气到飞升】06---重识类和对象(一)
|
3天前
|
存储 编译器 C语言
【C++从练气到飞升】02---初识类与对象
【C++从练气到飞升】02---初识类与对象
|
4天前
|
设计模式 算法 编译器
【C++入门到精通】特殊类的设计 |只能在堆 ( 栈 ) 上创建对象的类 |禁止拷贝和继承的类 [ C++入门 ]
【C++入门到精通】特殊类的设计 |只能在堆 ( 栈 ) 上创建对象的类 |禁止拷贝和继承的类 [ C++入门 ]
9 0

推荐镜像

更多