1. 程式人生 > >C++ 集合容器set

C++ 集合容器set

例子

// set::size
#include <iostream>
#include <set>

int main ()
{
  std::set<int> myints;
  std::cout << "0. size: " << myints.size() << '\n';

  for (int i=0; i<10; ++i) myints.insert(i);
  std::cout << "1. size: " << myints.size() << '\n';

  myints.insert (100);
  std::cout << "2. size: " << myints.size() << '\n';

  myints.erase(5);
  std::cout << "3. size: " << myints.size() << '\n';

  return 0;
}
1,迭代器 Iterator
 for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
    std::cout << *it<< std::endl;

2,容量 Capacity:

myset.empty() // 判斷是否為空
myints.size() //Returns the number of elements in the set container.
3,修改 Modifiers:
set<int> myset;
myset.insert(20); //插入指定元素
int myints[]= {5,10,15}; // 10 already in set, not inserted
myset.insert (myints,myints+3); //用陣列插入多個元素
myset.erase (40); //刪除指定元素
it = myset.find (60);
myset.erase (it, myset.end());//刪除範圍
myset.clear();   //清空
set1.swap(set2); //交換
4,操作 Operations:
find(); //查詢元素,返回迭代指標,找不到返回 iterator to set::end.
it=myset.find(20);
myset.erase (it);
myset.count(i) //計算set中i值的數量,有就返回1,沒有返回0

// set::find
#include <iostream>
#include <set>

int main ()
{
  std::set<int> myset;
  std::set<int>::iterator it;

  // set some initial values:
  for (int i=1; i<=5; i++) myset.insert(i*10);    // set: 10 20 30 40 50

  it=myset.find(20);
  myset.erase (it);
  myset.erase (myset.find(40));

  std::cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

demo

#include <iostream>     // std::cout  
#include <vector>       // std::vector  
#include <set>          
using namespace std;  
  
int main () {  
    int a[] = {32,71,12,45,26,80,53,33};  
    int b[]= {10,20,30,40,50};  
    int c[]= {11,22,33 };  
    vector< set<int> > vect;  
  
    set<int> first(a,a+8);        
    set<int> sec(b,b+5);   
    set<int> thrid(c,c+sizeof(c)/sizeof(int));   
      
    vect.push_back(first);  
    vect.push_back(sec);  
    vect.push_back(thrid);  
    cout<<"set :"<<endl;  
    for (vector<set<int> >::iterator it = vect.begin() ; it != vect.end(); ++it)    
    {  
        set<int>tem =*it;  
        for (std::set<int>::iterator st=tem.begin(); st!=tem.end(); ++st)    
            std::cout << *st<<"  ";    
        tem.clear();  
        cout<<endl;  
    }  
  
    getchar();  
    return 0;  
}