the STL std::set insert --Operator< Overloaded

来源:互联网 发布:2017人工智能 编辑:程序博客网 时间:2024/05/16 00:45

1.CplusCplus网站的c++ reference对set的insert函数的解释实例:

// set::insert (C++98)#include <iostream>#include <set>int main (){  std::set<int> myset;  std::set<int>::iterator it;  std::pair<std::set<int>::iterator,bool> ret;  // set some initial values:  for (int i=1; i<=5; ++i) myset.insert(i*10);    // set: 10 20 30 40 50  ret = myset.insert(20);               // no new element inserted  if (ret.second==false) it=ret.first;  // "it" now points to element 20  myset.insert (it,25);                 // max efficiency inserting  myset.insert (it,24);                 // max efficiency inserting  myset.insert (it,26);                 // no max efficiency inserting  int myints[]= {5,10,15};              // 10 already in set, not inserted  myset.insert (myints,myints+3);  std::cout << "myset contains:";  for (it=myset.begin(); it!=myset.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

Output:

myset contains: 5 10 15 20 24 25 26 30 40 50

2. 需要重写操作符 Operator<, 注意在函数前注明是友元函数:friend bool operator<(const Cmp &dest, const Cmp &src),要不然通不过编译:

more setOperatorOverload.cpp
<pre name="code" class="cpp">#include <iostream>#include <set>class Cmp{public:int a;char b;std::string str;friend bool operator<(const Cmp &dest, const Cmp &src){return dest.a < src.a;}};int main(void){std::set<Cmp> test1;std::set<Cmp> test2;Cmp temp;temp.a = 1;temp.b = 'b';temp.str = std::string("string");test1.insert(temp);temp.a++;test1.insert(temp);temp.a++;test1.insert(temp);std::set<Cmp>::iterator it = test1.begin();for(; it != test1.end(); it++){test2.insert(*it);}it = test2.begin();int i = 0;for(; it != test2.end(); it++){std::cout<<"test Output:"<< i++ << ", a:" << it->a << ", b:" << it->b << ", str:" << it->str <<std::endl;}return 0;}

./a.out

test Output:0, a:1, b:b, str:string
test Output:1, a:2, b:b, str:string
test Output:2, a:3, b:b, str:string



0 0
原创粉丝点击