set中放入结构体或者自定义对象注意的问题

老习惯,还是先上代码

class Pos
{
public:
	Pos(int x, int y) :
		_x(x), _y(y){}
	bool operator<(const Pos & another)const 
	{
		return  (_x > another._x || _x == another._x && _y > another._y);
	}
	void showPos()const
	{
		cout << "(" << _x << "," << _y << ")" << endl;
	}
	void showPos()
	{
		cout << "(" << _x << "," << _y << ")" << endl;
	}

private:
	int _x;
	int _y;
};

typedef set<Pos> SetPos;

int main()
{
	Pos p1(1, 2), p2(3, 4), p3(5, 6) , p4(2, 7);

	SetPos posSet;
	posSet.insert(p1);
	posSet.insert(p2);
	posSet.insert(p3);
	posSet.insert(p4);


	Pos p5(4, 3);
	std::pair<SetPos::iterator, bool> pairItr = posSet.insert(p5);
	const_cast<Pos&>(*(--pairItr.first)).showPos();
	 
	cout << endl;
	if (posSet.count(p5) > 0)
		posSet.erase(p5);

	for (SetPos::iterator itr = posSet.begin(); itr != posSet.end(); ++itr)
	{
		Pos& myPos = const_cast<Pos&>(*itr);
		myPos.showPos();
	}
	

	system("pause");
	return 0;
}

注意的地方:

1 set中放入结构体或者自定义对象时,要重载小于号,注意是 bool operator<(const A & )const 的形式(map一样要重载)

2 set 在插入类对象的时候(insert()),对象会自动转换为const,相当于插入了const对象,注意const 对象只能调用类中的const成员函数,所以,如果想调用非const成员函数,必须去const const_cast<Pos&>(*itr);

3 类似 1、5、 7。 与目标值3比较,想找到1的这种需求

Pos p5(4, 3);
std::pair<SetPos::iterator, bool> pairItr = posSet.insert(p5);
const_cast<Pos&>(*(--pairItr.first)).showPos();

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值