Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
May 19, 1998

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 <algorithm> 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.h
class 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
#include

using 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());
}

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap