平衡二叉檢索樹使用中序遍歷算法,檢索效率高於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
#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;
}