I have a class which looks like the following:
class A{
private:
int *a[10];
};
Now I want to have a map which will have the mentioned class as it's key.
map<A,int> visited;
How can I overload the less operator/write a compare function here so that the map can identify duplicate 2D arrays? I have written a overloader inside the class. But, it's treating objects containing duplicate arrays as different objects. This is the function I have written:
bool operator<(const A& other) const{
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(a[i][j]!=other.a[i][j])return true;
}
}
return false;
}
I can't find the problem in the code. Can somebody please help?
答案 0 :(得分:2)
bool operator<(const A& other) const{
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(a[i][j]==other.a[i][j]) continue;
return a[i][j]<other.a[i][j];
}
}
return false;
}
这应该适用于地图。但如果阵列很大,它可能会很慢。考虑编写一个哈希函数并使用unordered_map。