set的基本操作:
begin() 返回指向第一个元素的迭代器
clear() 清除所有元素
count() 返回某个值元素的个数
empty() 如果集合为空,返回true
end() 返回指向最后一个元素的迭代器
equal_range() 返回集合中与给定值相等的上下限的两个迭代器
erase() 删除集合中的元素
find() 返回一个指向被查找到元素的迭代器
get_allocator() 返回集合的分配器
insert() 在集合中插入元素
lower_bound() 返回指向大于(或等于)某值的第一个元素的迭代器
key_comp() 返回一个用于元素间值比较的函数
max_size() 返回集合能容纳的元素的最大限值
rbegin() 返回指向集合中最后一个元素的反向迭代器
rend() 返回指向集合中第一个元素的反向迭代器
size() 集合中元素的数目
swap() 交换两个集合变量
upper_bound() 返回大于某个值元素的迭代器
value_comp() 返回一个用于比较元素间的值的函数
#include <iostream>
#include <set>
using namespace std;
#include <vector>
using std::vector;
#include <string>
using std::string;
int main(){
vector<int> ivec;
for(vector<int>::size_type i = 0; i != 10; ++i)
{
ivec.push_back(i);
ivec.push_back(i);
}
set<int > iset(ivec.begin(),ivec.end());
cout << ivec.size() << endl;
cout << iset.size() << endl;
cout << "------------------------------" << endl;
cout << iset.count(1) << endl;
set<int>::iterator set_it = iset.find(1);
if(set_it != iset.end())
{
cout << *set_it << endl;
}
cout << "------------------------------" << endl;
set<int>::iterator si;
for (si=iset.begin(); si!= iset.end(); si++)
{
cout << *si <<" " << endl;
}
cout << "------------------------------" << endl;
set<string> set1;
set1.insert("the");
set1.insert("and");
set<string>::iterator ss;
for (ss=set1.begin(); ss!= set1.end(); ss++)
{
cout << *ss <<" " << endl;
}
cout << "------------------------------" << endl;
set1.erase("and");
set<string>::iterator ssErase;
for (ssErase=set1.begin(); ssErase!= set1.end(); ssErase++)
{
cout << *ssErase <<" " << endl;
}
return 0;
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ -o main main.cc
pateo@pateo-B86N53X:~/work/study$ ./main
20
10
------------------------------
1
1
------------------------------
0
1
2
3
4
5
6
7
8
9
------------------------------
and
the
------------------------------
the
pateo@pateo-B86N53X:~/work/study$