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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值