您的位置:首页 > 编程语言 > C语言/C++

C++语法基础--关联容器--set

2013-07-10 23:17 453 查看
1.set(#include<set>)

template < class T, // set::key_type/value_type

class Compare = less<T>, // set::key_compare/value_compare

class Alloc = allocator<T> > // set::allocator_type

> class set




2.构造函数


原型:

empty:

explicit set (const key_compare& comp = key_compare(),

const allocator_type& alloc = allocator_type());

range:

template <class InputIterator>

set (InputIterator first, InputIterator last,

const key_compare& comp = key_compare(),

const allocator_type& alloc = allocator_type());

copy:

set (const set& x)

Examples:

set<int> first; // empty set of ints

int myints[]= {10,20,30};

set<int> second (myints,myints+3); // range

set<int> third (second); // a copy of second

set<int> fourth (second.begin(), second.end());
// iterator ctor.

2.添加元素,insert()

*与map容器的操作一样,带一个参数的insert版本返回pair类型的对象,包含一个迭代器和一个bool值

原型:

single element :

pair<iterator,bool> insert (const value_type& val);

with hint:

iterator insert (iterator position, const value_type& val);

range :

template <class InputIterator>

void insert (InputIterator first, InputIterator last);

Examples:

int main ()

{

set<int> myset;

set<int>::iterator it;

pair<set<int>::iterator,bool> ret;

// set some initial values:

for (int i=1; i<=3; ++i)

{

myset.insert(i*10); // set: 10 20 30

}

ret = myset.insert(20); // no new element inserted

if (!ret.second)

{

it=ret.first; // "it" now points to element 20

}

myset.insert (it,15);

int myints[]= {5,10,15}; // 10,15 already in set, not inserted

myset.insert (myints,myints+3);

cout << "myset contains:"<<endl;

for (it=myset.begin(); it!=myset.end(); ++it)

{

cout << ' ' << *it; //5 10 15 20 30

}



return 0;

}

3.从set中获取元素find()

*set容器不提供下标操作符

*正如不能修改map中元素的键一样,在获得指向set中某元素的迭代器后,只能对其做读操作。

原型:

iterator find (const value_type& val) const;

Examples:

int main ()

{

set<int> myset;

set<int>::iterator it;

// set some initial values:

for (int i=1; i<=3; i++)

{

myset.insert(i*10); // set: 10 20 30

}

it=myset.find(20);

myset.erase (it);



cout << "myset contains:"<<endl;

for (it=myset.begin(); it!=myset.end(); ++it)

{

std::cout << ' ' << *it; //10 30

}



return 0;

}

4.简单判断某个元素是否存在count().

*与map容器一样,count的返回值只能是1或0

原型:

size_type count (const value_type& val) const;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: