Chinaunix

标题: 出学者紧急求助:关于c++ stl--map的使用问题, [打印本页]

作者: 谢灵运    时间: 2007-06-28 14:03
标题: 出学者紧急求助:关于c++ stl--map的使用问题,
#include "stdafx.h"
#include <utility>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;

struct Item
{
        string name;
        string cd;
   
        Item(const string &name,const string &cd)
        {
                this->name=name;
                this->cd=cd;
        }

        bool operator==( const Item & object)
        {
                return this->cd == object.cd;
        }

        bool operator<( const Item & object)
        {
                return this->cd < object.cd;
        }
};

struct Area
{
        string name;
        string cd;

        Area(const string &name,const string &cd)
        {
                this->name=name;
                this->cd=cd;
        }

        bool operator==( const Area & object)
        {
                return this->cd == object.cd;
        }

        bool operator<( const Area & object)
        {
                return this->cd < object.cd;
        }
};



int _tmain(int argc, _TCHAR* argv[])
{
        map< Item,int > ItemPosition;

        map< Area, vector<string> > ResultMap;

        map< Area, vector<int> > AreaFlag;
    //
    vector<int> aa;
    Area bb("ss","sss");
        AreaFlag.insert(make_pair(bb,aa));

        return 0;
}

错误提示:
1        error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Area' (or there is no acceptable conversion)        d:\microsoft visual studio 8\vc\include\functional        143       

请各位前辈赐教,谢谢
作者: wolf0403    时间: 2007-06-28 14:09
Item 操作符不能在 const Item 对象/引用上调用
作者: 谢灵运    时间: 2007-06-28 14:13
确实疏漏了,多谢前辈!

[ 本帖最后由 谢灵运 于 2007-6-28 14:17 编辑 ]
作者: antonym55    时间: 2007-06-28 15:30
原帖由 wolf0403 于 2007-6-28 14:09 发表
Item 操作符不能在 const Item 对象/引用上调用

呵呵,高人说话总是这么羞涩难懂。

第一次见到这种问题(有点孤陋寡闻)

g++ 会给出下面的错误提示, 第一行内容如下(节选)
In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Area]’:


而你的是
bool operator<( const Area & object)


少了一个 const, 改成下面这种形式就OK了
bool operator<( const Area & object) const

作者: cookis    时间: 2007-06-28 17:15
两种都要定义吧




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2