C++-STL中set的常用方法


關於C++-STL-set的常用函數和方法

set模板類在頭文件 中使用前需要先引入頭文件。

set集合容器實現了紅黑樹(Red-Black Tree)的平衡二叉檢索樹的數據結構,在插入元素時,它會自動調整二叉樹的排列,把該元素放到適當的位置,以確保每個樹根節點的鍵值大於左子樹所有節點的鍵值,而小於右子樹所有節點的鍵值;另外,還確保根節點左子樹的高度與右子樹的高度相等,這樣,二叉樹的高度最小,從而檢索速度最快。要注意的是,它不會重復插入相同鍵值的元素,而采取忽略處理。

關於set的基本操作

s.begin()       //  返回指向第一個元素的迭代器
s.clear()       //  清除所有元素
s.count()       //  返回某個值元素的個數
s.empty()       //  如果集合為空,返回true(真)
s.end()         //  返回指向最后一個元素之后的迭代器,不是最后一個元素
s.equal_range() //  返回集合中與給定值相等的上下限的兩個迭代器
s.erase()       //  刪除集合中的元素
s.find()        //  返回一個指向被查找到元素的迭代器
s.get_allocator()   //  返回集合的分配器
s.insert()      //  在集合中插入元素
s.lower_bound() //  返回指向大於(或等於)某值的第一個元素的迭代器
s.key_comp()    //  返回一個用於元素間值比較的函數
s.max_size()    //  返回集合能容納的元素的最大限值
s.rbegin()      //  返回指向集合中最后一個元素的反向迭代器
s.rend()        //  返回指向集合中第一個元素的反向迭代器
s.size()        //  集合中元素的數目
s.swap()        //  交換兩個集合變量
s.upper_bound() //  返回大於某個值元素的迭代器
s.value_comp()  //  返回一個用於比較元素間的值的函數

set容器的創建

set<type> 容器名稱

例如:
1. 未初始化大小
set<int> s;

2. 初始化大小
set<int> s(n);

set<int> s; s.resize(n); // n 表示所申請的大小

插入元素

#include <iostream>
#include <set>
using namespace std;
set<int> s;
int main()
{
	s.insert(1);
	s.insert(2);
	s.insert(3);
}

遍歷容器

有兩種方法

  1. 使用auto關鍵字獲取迭代器

  2. 創建set ::iterator it;

#include <iostream>
#include <set>
#include <vector>
using namespace std;
set<int> s;
int main()
{
	for(int i = 0;i < 10;i ++)
		s.insert(i);
	// 第一種方式
	for(auto it = s.begin() ; it != s.end() ;it ++){
		printf("%d ", *it);
	}
	cout << endl;
	// 第二種方式
	set<int>::iterator it;
	for(it = s.begin() ; it != s.end() ; it++){
		cout << *it << " ";
	}
	return 0;
}

輸出結果

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

查找元素

查找元素的方法和返回類型經常會用到需要熟記!
find() 方法查找指定的元素並返回,查找值的迭代器。
如果沒有找到則會返回end()!!

#include <iostream>
#include <set>
#include <vector>
using namespace std;
set<int> s;
int main()
{
	for(int i = 0;i < 10;i ++)
		s.insert(i);
	// 第一種方式
	for(auto it = s.begin() ; it != s.end() ;it ++){
		printf("%d ", *it);
	}
	cout << endl;
	// 第二種方式
	set<int>::iterator it;
	for(it = s.begin() ; it != s.end() ; it++){
		cout << *it << " ";
	}

	if(s.find(5) != s.end()){
		printf("找到該元素\n");
	}
	return 0;
}

刪除元素

erase()方法刪除集合中的指定元素

#include <iostream>
#include <set>
#include <vector>
using namespace std;
set<int> s;
int main()
{
	for(int i = 0;i < 10;i ++)
		s.insert(i);
	// 第一種方式
	for(auto it = s.begin() ; it != s.end() ;it ++){
		printf("%d ", *it);
	}
	cout << endl;
	// 第二種方式
	set<int>::iterator it;
	for(it = s.begin() ; it != s.end() ; it++){
		cout << *it << " ";
	}

	if(s.find(5) != s.end())
	{
		printf("find\n");
	}
	s.erase(5);
	for(auto it = s.begin() ; it != s.end() ;it ++){
		printf("%d ", *it);
	}
	return 0;
}

參考內容

https://blog.csdn.net/love20165104027/article/details/81510406


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM