map(op)这种构造函数
map这个容器的构造函数很多,其中一个是: map(op)一直没机会体会这种构造函数,于是写了个程序测试一下: 发现无法编译,网上一查询, 有人说:map只能够按照key来排序,既然按照key排序,那么提供map(op)这种方式作甚?class YuanGong{ unsigned int m_ID; string m_strName;public: YuanGong(unsigned int id, string strName):m_ID(id),m_strName(strName){}public: unsigned int GetID() const { return m_ID; } string GetName() const { return m_strName; } friend ostream& operator<<(ostream& o, YuanGong const& obj) { o<<obj.m_ID<<" "<<obj.m_strName<<endl; return o; }};class YuanGongCompare{public: /*bool operator()(YuanGong const& obj1,YuanGong const& obj2 ) { return (obj1.GetName()>obj2.GetName())?true:false; }*/ bool operator()(YuanGong const& obj1,YuanGong const& obj2 ) { return (obj1.GetID()>obj2.GetID())?true:false; }};int main(){ map<unsigned int,YuanGong,YuanGongCompare> myMap; unsigned int const n=3; YuanGong obj[n]={YuanGong(23,"csdn"),YuanGong(623,"c34sdn"),YuanGong(334,"cbhhsdn")}; unsigned int pos; for(pos=0; pos<n; pos++) { myMap.insert(make_pair(obj[pos].GetID(), obj[pos].GetName())); } //copy(myMap.begin(),myMap.end(), ostream_iterator<YuanGong>(cout," ")); return 0;}
class YuanGongCompare{public: /*bool operator()(YuanGong const& obj1,YuanGong const& obj2 ) { return (obj1.GetName()>obj2.GetName())?true:false; }*/ bool operator()(const int &obj1,const int &obj2 ) //注意这里 函数形参应该与map键类型一致 因为 在map内部 是使用的键的值作为形参传给比较器 { return obj1>obj2; //这样写就可以了 }};
[解决办法]
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map;
这是关于比较器的描述:
Compare: Comparison class: A class that takes two arguments of the key type and returns a bool. The expression comp(a,b), where comp is an object of this comparison class and a and b are key values, shall return true if a is to be placed at an earlier position than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to less<Key>, which returns the same as applying the less-than operator (a<b)
以下是使用例子
#include <iostream>#include <map>using namespace std;bool fncomp (char lhs, char rhs) {return lhs<rhs;}struct classcomp { bool operator() (const char& lhs, const char& rhs) const {return lhs<rhs;}};int main (){ map<char,int> first; first['a']=10; first['b']=30; first['c']=50; first['d']=70; map<char,int> second (first.begin(),first.end()); map<char,int> third (second); map<char,int,classcomp> fourth; // class as Compare bool(*fn_pt)(char,char) = fncomp; map<char,int,bool(*)(char,char)> fifth (fn_pt); // function pointer as Compare return 0;}
------解决方案--------------------
1, key是unsigned int, 你的operator()传入YuanGong? 2, operator()末尾加上const.3, 你的map到底是存uint->string还是uint->YuanGong?