My source code from gist
#include <iostream>
#include <map>
using namespace std;
class object ;
class object
{
public:
static int count;
int value1;
int value2;
int value3;
int value4;
object():value1(0),value2(0),value3(0),value4(0)
{
++object::count;
}
object(int a, int b,int c,int d): value1(a),value2(b),value3(c),value4(d)
{
cout << "(" << a << "," << b << "," << c << "," << d << ")" << endl;
++object::count;
}
object(const object & objectA):value1(objectA.value1),value2(objectA.value2),value3(objectA.value3),value4(objectA.value4)
{
}
object & operator = (const object & objectA)
{
this->value1=objectA.value1;
this->value2=objectA.value2;
this->value3=objectA.value3;
this->value4=objectA.value4;
return *this;
}
};
int object::count=0;
class Mycmp
{
public:
bool operator()(const object & A,const object & B) const
{
//return !((A.value1==B.value1) && (A.value2==B.value2));
return (A.value1<B.value1) || (A.value2<B.value2) || (A.value3<B.value3) || (A.value4<B.value4);
}
};
int main(int argc , char * argv[])
{
cout << "INPUT:" << endl;
/* Set input information */
object objectA(1,2,1,3),
objectB(2,2,1,3),
objectC(3,2,1,2),
objectD(3,2,1,2),
objectE(1,3,0,3),
objectF(1,3,1,1),
objectG(2,1,1,1),
objectH(3,2,1,8),
objectI(2,1,2,7),
objectJ(2,1,1,1),
objectK(2,2,0,8),
objectL(2,2,1,3);
cout << "INTPUT SIZE:" << object::count << endl;
map<object,int,Mycmp> MyMap;
MyMap.insert(pair<object,int>(objectA,1));
MyMap.insert(pair<object,int>(objectB,2));
MyMap.insert(pair<object,int>(objectC,2));
MyMap.insert(pair<object,int>(objectD,2));
MyMap.insert(pair<object,int>(objectE,2));
MyMap.insert(pair<object,int>(objectF,2));
MyMap.insert(pair<object,int>(objectG,2));
MyMap.insert(pair<object,int>(objectH,2));
MyMap.insert(pair<object,int>(objectI,2));
MyMap.insert(pair<object,int>(objectJ,2));
MyMap.insert(pair<object,int>(objectK,2));
MyMap.insert(pair<object,int>(objectL,2));
cout << "AFTER INSERT INFORMATION:" << endl;
for(map<object,int>::iterator it = MyMap.begin(); it!=MyMap.end() ; ++it)
{
cout << "(" << it->first.value1 << "," << it->first.value2 << "," << it->first.value3 << "," << it->first.value4 << ")" << endl;
}
cout << "INSERT SIZE:" << MyMap.size() << endl ;
return 0;
}
輸出結果:
INPUT:
(1,2,1,3)
(2,2,1,3)
(3,2,1,2)
(3,2,1,2)
(1,3,0,3)
(1,3,1,1)
(2,1,1,1)
(3,2,1,8)
(2,1,2,7)
(2,1,1,1)
(2,2,0,8)
(2,2,1,3)
INTPUT SIZE:12
AFTER INSERT INFORMATION:
(2,2,0,8)
(2,1,1,1)
(2,2,1,3)
(2,1,2,7)
(1,3,1,1)
(1,3,0,3)
(3,2,1,2)
(1,2,1,3)
(2,2,1,3)
(3,2,1,8)
INSERT SIZE:10
補充:
上述的 operator () ,對C++不太熟的讀者應該很陌生。(就連我自己也第一次見到,可能是我之前大多是寫operator +,<<,= 為主的功能)
其實他的執行方式大約如下:
MyCmp objectCmp;
bool check=objectCmp(objectA,objectB); /* Using () operator! */
那些Operator加起來都可以去實做代數學的+,* 等運算了。
想要知道更多operator,請按此。
很有趣的問題XD
回覆刪除