老习惯,还是先上代码
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();