遍历存放类或结构体的set 在做传教士和野人问题时,用到了set存放类,所以在这里先测试一下set的功能是否正常。在正确重载 " < " 后,打印变成了一个问题。本来是想再重载 " << " 或者输出运算符,没成功。后来又在网上找了替代办法。
关键代码
for(set<State>::iterator it = s.begin(); it != s.end() ;it++)
{
State tmp = (State)(*it);
tmp.printState();
}
完整代码
#include <iostream>
using namespace std;
#include <set>
#include <cstring>
class State
{
public:
int mission;
int savage;
int boat;
void setState(int s1,int s2,int s3)
{
mission = s1;
savage = s2;
boat = s3;
}
bool operator < (const State b) const {
if (mission < b.mission)
return true;
else if (mission == b.mission)
{
if (savage < b.savage)
return true;
else if (savage == b.savage)
{
return boat < b.boat;
}
else return false;
}
else return false;
}
void printState()
{
cout << "(" << mission << "," << savage << "," << boat << ")" << endl;
}
};
set<State> s;
int main()
{
State s1;
State s2;
State s3;
State s4;
State s5;
State s6;
s1.setState(1,2,3);
s2.setState(4,5,6);
s3.setState(4,4,3);
s4.setState(2,1,3);
s5.setState(1,2,2);
s6.setState(4,4,3);
s.insert(s1);
s.insert(s2);
s.insert(s3);
s.insert(s4);
s.insert(s5);
s.insert(s6);
cout<<s.size()<<endl;
for(set<State>::iterator it = s.begin(); it != s.end() ;it++)
{
State tmp = (State)(*it);
tmp.printState();
}
return 0;
}
参考博客 set集合(如何自定义储存数据类型)
总结 在遇到STL嵌套结构体或者类时,或许都可以用这个办法打印。
|