2010-10-25 68 views
0

我在重载比较运算符时遇到麻烦,以便以这种方式比较两个pair结构:模拟类的重载比较运算符

typedef pair<string, unsigned int> INDEX; 
bool operator>(INDEX &v1, INDEX &v2) 
{ 
    if(v1.second == v2.second) //if integer parts are equal 
    { 
     //string that comes earlier in the dictionary should be larger 
     return v1.first < v2.first; 
    } 
    return v1.second > v2.second; 
} 

实际比较发生在fixUp(CBTNODE hole)fixUp(CBTNODE hole)内,BinaryHeap类的成员函数,它是派生类of CompleteBinaryTreeT将被实例化为INDEX类型,typedefpair<string, unsigned int>

换句话说,两对之间的比较:(“a.txt”,42)>(“b.txt”,42)应该返回true。

我试图以两种不同的方式在类声明之外重载operator>,但它们都不起作用:

  1. bool operator>(INDEX &v1, INDEX &v2);
  2. bool operator>(BinaryHeap<T> &v1, BinaryHeap<T> &v2);

任何帮助将不胜感激!

Z.Zen

以下是声明:

typedef int CBTNODE; 

template <typename T> 
class CompleteBinaryTree { 
public: 
    //Initializes an empty binary tree 
    CompleteBinaryTree(int initialSize = 10); 

    //Destructor 
    ~CompleteBinaryTree(); 

    //Returns the element of the CBT pointed to by node. Behavior is undefined 
    //if node does not exist. 
    T element(CBTNODE node); 

protected: 
    T *data; 
    int numElts, maxElts; 
}; 

typedef pair<string, unsigned int> INDEX; 

template <typename T> 
class BinaryHeap : public CompleteBinaryTree<T> 
{ 
    public: 
     //Maintain heap property with bottom up heapify method. 
     void fixUp(CBTNODE hole); 
}; 
bool operator>(INDEX &v1, INDEX &v2); 

实现:

template <typename T> 
T CompleteBinaryTree<T>::element(CBTNODE node) { 
    assert(node >= 0); 
    assert(node < numElts); 
    return data[node]; 
} 

template <typename T> 
void BinaryHeap<T>::fixUp(CBTNODE hole) 
{ 
    T tmp = this->element(hole);  
    while(hole > 0 && this->element(hole/2) < tmp) 
    { 
     //do stuff 
    } 
} 

bool operator>(INDEX &v1, INDEX &v2) 
{ 
    if(v1.second == v2.second) //if two have same relevance 
    { 
     return v1.first < v2.first; 
    } 
    return v1.second > v2.second; 
} 
+0

你得到了什么错误,并在该行? – Chubsdad 2010-10-25 05:41:49

+0

是否真的需要定义'bool操作符'(INDEX&v1,INDEX &v2);'。不配对类是否有比较操作符? – Chubsdad 2010-10-25 05:44:09

+0

它编译了但它没有做它应该做的事情。做比较:对<'a', 42>>对<'b', 42>,它返回false,根据我的定义,它应该返回true。该对的第一个元素是一个C++字符串,第二个元素是一个int。 – 2010-10-25 05:45:35

回答

1

临时,如element FUNC的结果,不能被绑定到一参考非const,例如您的operator>的正式参数。

声明它正是如此:

bool operator>(INDEX const& v1, INDEX const& v2) 

但是,你目前的实现似乎并不为operator>是正确的。

虽然我在这里,但你想要的却是operator<,因为那是标准算法所要求的。也许再加上operator==(因为从operator<合成它效率低)。有了这两种关系,可以相对有效地检查。

顺便说一句,如果你停止使用ALL UPPERCASE命名所有其他的宏(参见FAQ),那么你可以避免无意中与宏命名冲突。

干杯&心连心,

+0

非常感谢你!它像一个魅力。我实际上实现了所有比较运算符,但为了简单起见,我只在我的问题中显示了一个。 – 2010-10-25 07:21:24

+0

嗯。它没有引起我关于'const'的提示,因为OP提到代码的构建和运行良好。 – Chubsdad 2010-10-25 07:59:03

1

不要的typedef INDEX,是明确的:

template<class F, class S> 
struct Index { 
    std::pair<F, S> Value; 
    Index(const std::pair<F, S>& pValue) 
    : Value(pValue) {} 
}; 

template<class F, class S> 
bool operator<(const Index<F, S>& pLeft, const Index<F, S>& pRight) { 
    // your implementation... 
}