C/C++——set的基本操作總結
阿新 • • 發佈:2019-02-15
set容器中只能儲存鍵,是單純的鍵的集合,其中鍵是不能重複的。
set支援大部分的map的操作,但是set不支援下標的操作,而且沒有定義mapped_type型別。
下面簡單總結下set容器的操作:
1、set物件的定義和初始化
set物件的定義和初始化方法包括:
set<T> s;
set<T> s(s1);
set<T> s(b, e);
其中,b和e分別為迭代器的開始和結束的標記。
例如:
#include <stdio.h>
#include <vector>
#include <set>
using namespace std;
int main(){
vector<int> v;
for (int i = 0; i < 10; i++){
v.push_back(i);
v.push_back(i);
}
set<int> s(v.begin(), v.end());
printf("%d\n", v.size());
printf("%d\n", s.size());
return 0;
}
注意:鍵是不能重複的。
2、set中資料的插入
與map不同,set中資料只能通過insert()
函式進行插入。
例如:
#include <stdio.h>
#include <vector>
#include <set>
using namespace std;
int main(){
vector<int> v;
for (int i = 0; i < 10; i++){
v.push_back(i);
v.push_back(i);
}
set <int> s;
s.insert(v.begin(), v.end());
set<int>::iterator it;
for (it = s.begin(); it != s.end(); it++){
printf("%d\t", *it);
}
printf("\n");
s.insert(10);
for (it = s.begin(); it != s.end(); it++){
printf("%d\t", *it);
}
printf("\n");
return 0;
}
3、從set中查詢和讀取元素
從set中查詢同樣可以使用count()
函式和find()
函式,兩者的區別在之前的map中已經總結。
例如:
#include <stdio.h>
#include <vector>
#include <set>
using namespace std;
int main(){
vector<int> v;
for (int i = 0; i < 10; i++){
v.push_back(i);
v.push_back(i);
}
set<int> s;
s.insert(v.begin(), v.end());
set<int>::iterator it;
for (it = s.begin(); it != s.end(); it++){
printf("%d\t", *it);
}
printf("\n");
printf("%d\n", s.count(9));
printf("%d\n", *(s.find(9)));
return 0;
}
4、從set中刪除元素
從set中刪除元素使用到的函式是erase()
函式,主要有以下的幾種形式:
erase(k);
erase(p);
erase(b, e);
其中,p表示的迭代器指向的元素,b和e分別是迭代器的開始和結束。
例如:
#include <stdio.h>
#include <vector>
#include <set>
using namespace std;
int main(){
vector<int> v;
for (int i = 0; i < 10; i++){
v.push_back(i);
v.push_back(i);
}
set<int> s(v.begin(), v.end());
set<int>::iterator it;
for (it = s.begin(); it != s.end(); it++){
if (*it == 5){
break;
}
}
s.erase(it, s.end());
set<int>::iterator it_1;
for (it_1 = s.begin(); it_1 != s.end(); it_1++){
printf("%d\t", *it_1);
}
printf("\n");
return 0;
}