STL中set結構的使用

set集合容器:實現了紅黑樹的平衡二叉檢索樹的數據結構,插入元素時,它會自動調整二叉樹的排列,把元素放到適當的位置,以保證每個子樹根節點鍵值大於左子樹所有節點的鍵值,小於右子樹所有節點的鍵值;另外,還得保證根節點左子樹的高度與右子樹高度相等。
平衡二叉檢索樹使用中序遍歷算法,檢索效率高於vector、deque和list等容器,另外使用中序遍歷可將鍵值按照從小到大遍歷出來。

構造set集合主要目的是爲了快速檢索,不可直接去修改鍵值。

這個和上一個博客中Map的用法相似,一個代碼,把常用的方法試了一遍。

#include<iostream>
#include<set>
#include<string> 

using namespace std;

int main()
{
	set<string> st;
	string str[4];
	str[0] = "apple";
	str[1] = "banana";
	str[2] = "orange";
	str[3] = "orange";
	
	//往set集合中加入元素。 
	//當遍歷出來發現是已經排好序的,默認升序排序。
	//裏面的值是唯一的,所以str[3]插入是無效的,遍歷就知道了,可用於統計文章單詞數 
	
	
	//如同map,判斷是否插入數據成功。 
	pair<set<string>::iterator, bool> success; 
	success = st.insert(str[1]); 
	if(success.second==true)
	{
		cout<<"success"<<endl;
	}
	st.insert(str[0]);
	st.insert(str[2]);
	st.insert(str[3]);
	
	//遍歷一個set集合。 
	set<string>::iterator it;
	for(it=st.begin();it!=st.end();it++)
	{
		//記住iterator本質上類似於一個指針集合,裏面存着值對象,帶*取值 
		cout<< *it << endl;
		 
	}
	cout<<st.size()<<endl;
	
	//刪除set元素中的某一元素。 
	st.erase("orange"); 
	for(it=st.begin();it!=st.end();it++)
	{
		//記住iterator本質上類似於一個指針集合,裏面存着值對象,帶*取值 
		cout<< *it << endl;
		 
	}
	cout<<st.size()<<endl;
	
	//查找set某一元素是否存在
	//因爲集合中值唯一,所以只會返回0|1; 
	cout<<st.count("banana")<<endl; 
	
	//判斷是否爲空 
	if(!st.empty())
	{
		//清空set 
		st.clear();
	}

	return 0;
} 

這種類型的使用在日常比賽中常用的是,增刪查。如統計文章中單詞個數,重複的將不會對集合數據產生影響。

如例題 hdu2072

單詞數

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 51789    Accepted Submission(s): 12737


Problem Description
lily的好朋友xiaoou333最近很空,他想了一件沒有什麼意義的事情,就是統計一篇文章裏不同單詞的總數。下面你的任務是幫助xiaoou333解決這個問題。
 

Input
有多組數據,每組一行,每組就是一篇小文章。每篇小文章都是由小寫字母和空格組成,沒有標點符號,遇到#時表示輸入結束。
 

Output
每組只輸出一個整數,其單獨成行,該整數代表一篇文章裏不同單詞的總數。
 

Sample Input
you are my friend #
 

Sample Output
4
 
AC代碼,

#include<iostream>
#include<sstream>
#include<cstring>
#include<set>
using namespace std;


int main()
{
	string s;
	while(getline(cin,s) && s!="#")
	{
		istringstream str(s);
		string sp;
		set<string> words;
		while(str>>sp)
		{
			words.insert(sp);
		}	
		cout<<words.size()<<endl;
	}	
	return 0;
}

在這裏面,我用到一個陌生的數據類  istringstream 是將字符串變成字符串迭代器一樣,將字符串流在依次拿出,比較好的是,它不會將空格作爲流。這樣就實現了字符串的空格切割。

這個屬於#include<sstream>以後我會詳細學習,這裏先就題論題,寫個小測試代碼,幫助理解。

#include<iostream>
#include<set>
#include<sstream>
#include<cstring>
using namespace std;
int main()
{
	string str = "i am a boy";
	istringstream its(str);
	string s;
	while(its>>s)
	{
		cout<<s<<endl;
	}
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章