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
- the STL std::set insert --Operator< Overloaded
- std::map [] operator 和 insert 的区别
- STL std::set内存映像
- about set insert in stl
- no instance of overloaded function "std::tr1::bind" matches the argument list
- STL set的使用 less function override < operator
- C++ what operator can be overloaded?
- 高效的使用stl::map和std::set
- get_lantern::std::operator
- std::Set
- std::set
- std::set
- std::set
- std::set
- std::map&&std::set
- stl(四)------如何对map进行赋值std::map::operator=
- STL中set的insert操作的返回值
- std stl
- ShortcutMapper 是应用程序的键盘快捷键
- MFC为子对话框添加OnInitDialog函数
- POJ 3984 迷宫问题
- hdu 4362 Dragon Ball(优先队列+dp)
- learn with python-第十一章:文件和异常
- the STL std::set insert --Operator< Overloaded
- OOP版电子词典
- 项目中发现的一些关于JavaScript中JSON的注意点
- GDI+屏幕截图内存BMP转JPG,JPG再转IStream流,IStream流再转BYTE;
- hadoop_day1
- 多线程
- 今日作息及食谱(6.4)
- 关于移动互联数据挖掘在智慧旅游方面的应用
- Struts2快速入门实例代码教程