구조체가 STL 맵의 키일 때 주의해야 할 것은 무엇입니까?(모 회사 채용 면접시험)
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Info
{
string name;
int score;
};
int main()
{
Info a, b;
a.name = "eric";
a.score = 90;
b.name = "cat";
b.score = 85;
map<Info, int> m;
m[a] = 1;
m[b] = 2;
return 0;
} 실행해 보니 프로그램에 오류가 있었다.왜 그랬을까?원래 맵에 있어서 키는 질서가 있어야 한다. 즉, 키와 키 사이를 비교할 수 있어야 하기 때문에 <번호를 다시 불러야 한다. 따라서 상기 프로그램 오류는 다음과 같이 변경해야 한다.
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Info
{
string name;
int score;
bool operator< (const Info &x) const
{
return score < x.score;
}
};
int main()
{
Info a, b;
a.name = "eric";
a.score = 90;
b.name = "cat";
b.score = 85;
map<Info, int> m;
m[a] = 1;
m[b] = 2;
map<Info, int>::iterator it;
for(it = m.begin(); it != m.end(); it++)
{
cout << it->first.name << endl;
}
return 0;
}
올바른 작동 결과:cat eric
OK, 본고는 여기까지 논의했는데 관건은 맵의'키워드 질서'에 대한 충분한 인식이다.