有关使用map的错误

7 篇文章 0 订阅
3 篇文章 0 订阅

最近刚刚开始使用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]。因此,就更需要定义<了!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值