最近刚刚开始使用map,运行时出现了一个错误,程序和错误代码如下:
#include "Point3D.h"
#include <map>
void main(){
int num_vertex = 10;
Point3D *vertices = new Point3D[num_vertex];
for (int i=0; i<num_vertex; i+=3)
{
vertices[i].x = i;
vertices[i].y = i+1;
vertices[i].z = i+2;
}
map<Point3D, Point3D> edges;
edges.insert(std::make_pair(vertices[0],vertices[1]));
}
:\program files\microsoft_visual_studio_10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const Point3D'
1> d:\program files\microsoft_visual_studio_10.0\vc\include\memory(2582) : see declaration of 'std::operator <'
1>d:\program files\microsoft_visual_studio_10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const Point3D'
1> d:\program files\microsoft_visual_studio_10.0\vc\include\xutility(1356) : see declaration of 'std::operator <'
1>d:\program files\microsoft_visual_studio_10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const Point3D'
1> d:\program files\microsoft_visual_studio_10.0\vc\include\xutility(1179) : see declaration of 'std::operator <'
1>d:\program files\microsoft_visual_studio_10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const Point3D'
1> d:\program files\microsoft_visual_studio_10.0\vc\include\utility(318) : see declaration of 'std::operator <'
1>d:\program files\microsoft_visual_studio_10.0\vc\include\xfunctional(125): error C2676: binary '<' : 'const Point3D' does not define this operator or a conversion to a type acceptable to the predefined operator
错误信息提示我类Point3D没有定义'<',起初不知道这是什么意思,花了很多时间查看代码,仍没有找出错误。
后来转念一想,map有提供元素的比较操作,因此,使用map的类型需要有<的定义才能使用map。
于是在类Point3D中加入了对<的重载运算符,程序一下就编译通过了。
追加:
事实上,在更仔细的调试过程中发现,之所以要定义<,是因为map在插入元素的时候会根据你所定义的<符号对元素进行排序,而不是按插入的时间顺序排序。
即,如果map v里面已经有4个元素v[0]-v[3],如果新插入的元素比v[3]要小,比v[2]要大,则新元素变成v[3],而原先的v[3]变成v[4]。因此,就更需要定义<了!