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

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;
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值