dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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
Thanks for your registration, follow us on our social networks to keep up-to-date