为模板类重载比较运算符
我在重载比较运算符时遇到了麻烦,以便以这种方式比较两个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;
}
实际的比较发生在BinaryHeap
类的一个成员函数fixUp(CBTNODE hole)
内的this->element(hole/2) < this->element(hole)
,它是CompleteBinaryTree
的派生类。 该T
将被实例化作为类型INDEX
,这是typedef
ED作为pair<string, unsigned int>
。
换句话说,两对之间的比较:(“a.txt”,42)>(“b.txt”,42)应该返回true。
我试图用两种不同的方式在类声明外重载operator>
,但它们都没有工作:
bool operator>(INDEX &v1, INDEX &v2);
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;
}
临时的,比如element
func的结果,不能绑定到对非const
的引用,比如你的operator>
的形式参数。
如此声明:
bool operator>( INDEX const& v1, INDEX const& v2 )
但是,您提供的实现对于operator>
似乎并不正确。
而当我在这时,你想要的是真正的operator<
而不是标准算法所需的那个。 也许与operator==
相结合(因为从operator<
合成它效率低)。 有了这两种关系,可以相对有效地检查。
顺便说一句,如果您不再使用ALL UPPERCASE名称来设置其他宏(请参阅常见问题解答),那么您可以避免无意中与宏进行名称冲突。
干杯&hth。,
不要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...
}
链接地址: http://www.djcxy.com/p/73057.html