devxlogo

vector<> members must define < and == operators

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());}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist