#1013. STL之set

STL之set

set

可以认为是数学中 "集合" 的概念,可以存储同一类型的数据,且具备互异性。因此可使用 set 进行数据 "去重" 操作。

但又与 "集合" 有所不同,集合是无序的,而 set 由于底层算法实现原因而内部自动有序

因此甚至在某些情况下,可以用 set 进行排序。

头文件set

创建容器set<类型> 容器名称

常用成员函数

set<int> st;
st.insert(data) 添加元素 data
st.size() 表示键的个数
st.find(key) 搜索这个键,若存在则返回其迭代器
st.clear() 表示清空容器元素
st.empty() 查看容器是否为空

Example

#include <iostream>
#include <set>

using namespace std;

int main () {
	
    set<int> val;
	cout << "向 val 插入 10 个 data 数据: ";
	for (int i=1; i<=10; i++) {
		int data;
		cin >> data;
		val.insert(data); 
	}
		
	// 准备一个迭代器,准备用与遍历 val
	set<int>::iterator it;
		
	// 迭代器从 begin() 起始迭代器位置遍历 val 容器,直到 end() 末尾迭代器 
	for (it = val.begin(); it != val.end(); it++) {
		cout << "元素:" << *it << "\n";     
	}
	cout << endl;
	// 迭代器 it 的使用类似指针,用 * 获得迭代器位置所代表的数据块
	
	cout << "===============\n";
	cout << "auto 遍历\n";
	for (auto it : val) {
		cout << it << " ";
	} 
	cout << endl;
	cout << "=====================\n";
	
	int findX;
	cout << "输入要寻找的数字:";
	cin >> findX;
	it = val.find(findX);
	if (it == val.end()) {
		cout << "集合中,没有 " << findX << endl;
	} else {
		cout << "集合中,存在 " << *it << endl;
	}

    return 0;
}

简单练习

明明的随机数

👆 善用 set 的天然有序与去重的性质

  1. 以下对 set<char> s; 添加元素正确的是 ?

{{ select(1) }}

  • s.insert('s');
  • s.insert("s");