I am creating a KeyValuePair class, and am running into some trouble when overloading the relational operators. It is my understanding that this is necessary for using the std sort functions (I am trying to have sort based on the values)
Here is the header:
template <typename K, typename V>
class KeyValuePair
{
public:
//factory
static KeyValuePair<K,V>* newKeyValuePair(K key, V value);
//getters
const K &Key() const;
const V &Value() const;
//setter
V &Value();
//The problem
bool operator<(const KeyValuePair<K,V> &rhs);
string toString();
~KeyValuePair(void);
private:
K key;
V value;
KeyValuePair(K key, V value);
KeyValuePair(void);
};
Here is the definition of the < function
template <typename K, typename V>
bool KeyValuePair<K,V>::operator<(const KeyValuePair<K,V> &rhs)
{
return value < rhs.Value();
}
And here is the main where I am just testing the functionality of the class.
int _tmain(int argc, _TCHAR* argv[])
{
KeyValuePair<char,int>* kvp1 = KeyValuePair<char, int>::newKeyValuePair('A',1);
KeyValuePair<char,int>* kvp2 = KeyValuePair<char,int>::newKeyValuePair('B',10);
cout << (kvp1 < kvp2) << "\n";
return 0;
}
I have a breakpoint at the < function in my KeyValuePair class, and it is never activated.
Any Ideas? Thanks in advance.
kvp1andkvp2are pointers toKeyValuePair<char, int>objects. They are not themselvesKeyValuePair<char, int>objects.*kvp1 < *kvp2would invoke your overloadedoperator<. You cannot overloadoperator<for two pointer types because the built-inoperator<for pointers will be used.std::paircan be used as a key-value pair. In any case, you almost certainly shouldn’t be dynamically creating objects of this type: you should prefer to avoid dynamic allocation wherever possible, especially explicit dynamic allocation. Instead, just useKeyValuePair<char, int>local variables: