set的基本操作

    技术2022-05-12  1

    #include <set>#include <iostream>#include <string>using namespace std;

    //元素不是结构体,自定义比较函数如下://struct comp//{// bool operator()(const int &a,const int &b){//  return a > b;// }//};

    //集合内元素是结构体,可以将比较函数写在结构体内:struct info { string name; float score; bool operator < (const info &a) const{  return a.score < score; }};

    int main(int argc,int **argv){

    //集合的创建和集合的扩展 //set<int,comp> s; //s.insert(8); //s.insert(1); //s.insert(12); //s.insert(6); //s.insert(8);

     set<info> s; info information;

     information.name = "张洪豪"; information.score = 80.5; s.insert(information);

     information.name = "陈红"; information.score = 90.5; s.insert(information);

     information.name = "何林林"; information.score = 95;    s.insert(information);

        //对集合的遍历! //set<int>::iterator iter ; //for (iter= s.begin();iter != s.end();++iter) // cout<<*iter<<" "; //cout<<endl;

    //对集合元素的反向遍历! //set<int>::reverse_iterator iter1; //for (iter1 = s.rbegin();iter1 != s.rend();++iter1) // cout<<*iter1<<" "; //cout<<endl;

    //对集合的删除 //set<int>::iterator iter ;    //s.erase(6); //for (iter= s.begin();iter != s.end();++iter) // cout<<*iter<<" "; //cout<<endl; //s.clear(); //cout<<s.size()<<endl;

    //集合元素的查找 //set<int>::iterator it ; //it = s.find(6); //if(it!=s.end()) // cout<<*it<<endl; //else // cout<<"can not find !"<<endl; //it = s.find(20); //if(it!=s.end()) // cout<<*it<<endl; //else // cout<<"can not find !"<<endl;

     //set<int,comp>::iterator iter; set<info>::iterator iter; for (iter = s.begin();iter!=s.end();++iter)  cout<<(*iter).name<<" : "<<(*iter).score<<endl; cout<<endl;    return 0;}


    最新回复(0)