set

阅读量: 254 编辑

在 C++ 中,std::set 是标准模板库(STL)里的一个关联容器,它以有序且唯一的方式存储元素。

std::set 中的元素是唯一的,若插入重复元素,插入操作会被忽略。

函数用法

  • set<int> s :声明一个set,内部升序排列

  • set< int, greater > s :声明一个set,内部降序排列

  • s.empty():判断集合是否为空集

  • s.size():返回集合的元素数量

  • s.count(e):返回 s 中元素 e 的具体数目,返回值不是 0 就是 1

  • s.find(e):查找元素 e ,s.find(e) != s.end() 表示找到元素

  • s.insert(e):将 e 插入到 set 中

  • s.erase(e):将 e 删除

  • s.begin():迭代器 set 的开始(地址位置)

  • s.end():迭代器 set 的结束(地址位置)

     通过迭代器,循环遍历元素
     for(set<int>::iterator it = s.begin(); it != s.end(); ++it){
         cout << *it << " ";
     }
    
  • s.erase(begin, end):将[begin, end)处的元素删除

  • s.insert(s1.begin(), s1.end()):将区间[begin, end)中的值插入到 s 中

参考程序

// 爱码岛编程
#include <bits/stdc++.h>
using namespace std;

int main(){
	
	set<int> s; // , greater<int> 
	
	//插入元素
	s.insert(10);
	s.insert(40);
	s.insert(50);
	s.insert(20);
	s.insert(10); 
	
	cout << s.size() << endl;
	cout << s.empty() << endl; 
	
	// 元素的个数(用于判断元素是否存在) 
	cout << s.count(40) << endl;
	if(s.count(40) == 1){
		cout << "存在" << endl;
	}
	
	// 查找元素,还没到结尾呢,就找到了 
	if(s.find(40) != s.end()){
		cout << "存在" << endl;
	}
	
	// 删除一个元素 
	s.erase(40); // 剩下的是:10 20 50
	
	// 遍历一个set
	for(set<int>::iterator it = s.begin(); it != s.end(); ++it){
		cout << *it << " ";
	}
	
	return 0;
}
爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司