vector<> members must define < and == operators

The STL vector<>, as well as other standard containers, support comparison and sorting of their members by calling the corresponding standard functions found in the header file. These functions rely on the relational operators such as == and < in order to accomplish that. In case of primitive types such as int, char and pointers, the built-in operators are already defined and will be used. User-defined types, however, require overloading of these operators in order to perform a meaningful comparison and sort:

 //file: Date.hclass Date { public: 	bool operator == (const Date& d)  const 	  { return d.Year()==year && d.Month()==month && d.Day()==day;}	bool operator < (const Date& Date) const;	};//file: myprog.cpp#include #include#includeusing namespace std;void main(){	Date d1, d2(1970);	vector  vd(10);	vd.push_back(d1);  vd.push_back(d2);//sort uses overloaded == and > of class Date	sort(vd.begin(), vd.end());}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: