473,783 Members | 2,317 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Operater < overloading for struct problem

Hello everyone,

I am having trouble overloading the < operator for an assignment. I
use a struct that contains information and I would like to sort this
structure using STL sort with my own criteria of sorting. Basically, I
would like to sort on visitor count of the Attraction structure.
However, it never uses the < overloaded operator with my code.

Handler.h:

#ifndef H_HANDLER //Guard
#define H_HANDLER

#include <iostream>
#include <vector>
using namespace std;

struct Attraction {
string name;
int visitors;
};

class Handler { //Define the class Handler

private:
vector<Attracti on*attractions ;
vector<Attracti on*>::iterator p ;

public: //Public functions
~Handler();
void addAttraction(s tring name, int visitors);
void printAttraction s();
};
#endif

and in the Handler.cpp I have:

Handler.cpp - snippet:

bool operator<(const Attraction& a,const Attraction& b){
return a.visitors < b.visitors;
}

Here is the function that performs the sort after adding a value:

void Handler::addAtt raction(string name, int visitors){

Attraction *attr;
attr=new Attraction();

attr->name=name;
attr->visitors=visit ors;
attractions.pus h_back(attr);
sort(attraction s.begin(),attra ctions.end());

}

However, whatever I do, it will never use the overloaded < operator
for sorting. What am I doing wrong? If I add the overloaded function
in the header it starts complaining because it will also be inserted
into the main program which is confusing since I have a guard around
the header file.

Regards,
Frank

Mar 1 '07 #1
14 2089
Frank wrote:
I am having trouble overloading the < operator for an assignment. I
use a struct that contains information and I would like to sort this
structure using STL sort with my own criteria of sorting. Basically, I
would like to sort on visitor count of the Attraction structure.
However, it never uses the < overloaded operator with my code.

Handler.h:

#ifndef H_HANDLER //Guard
#define H_HANDLER

#include <iostream>
#include <vector>
using namespace std;

struct Attraction {
string name;
int visitors;
};

class Handler { //Define the class Handler

private:
vector<Attracti on*attractions ;
vector<Attracti on*>::iterator p ;

public: //Public functions
~Handler();
void addAttraction(s tring name, int visitors);
void printAttraction s();
};
#endif

and in the Handler.cpp I have:

Handler.cpp - snippet:

bool operator<(const Attraction& a,const Attraction& b){
return a.visitors < b.visitors;
}

Here is the function that performs the sort after adding a value:

void Handler::addAtt raction(string name, int visitors){

Attraction *attr;
attr=new Attraction();

attr->name=name;
attr->visitors=visit ors;
attractions.pus h_back(attr);
sort(attraction s.begin(),attra ctions.end());

}

However, whatever I do, it will never use the overloaded < operator
for sorting. What am I doing wrong?
Your operator< is defined for _objects_, but your vector is storing
_pointers_. Drop the 'new', drop the pointers, keep objects, and
everything will be fine.

You can declare/define a local Attraction object in 'addAttraction'
and then push_back it, the vector will make a copy.
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 1 '07 #2
On Mar 1, 10:45 am, "Frank" <f.f.nee...@gma il.comwrote:
Hello everyone,

I am having trouble overloading the < operator for an assignment. I
use a struct that contains information and I would like to sort this
structure using STL sort with my own criteria of sorting. Basically, I
would like to sort on visitor count of the Attraction structure.
However, it never uses the < overloaded operator with my code.

Handler.h:

#ifndef H_HANDLER //Guard
#define H_HANDLER

#include <iostream>
#include <vector>
using namespace std;

struct Attraction {
string name;
int visitors;

};

class Handler { //Define the class Handler

private:
vector<Attracti on*attractions ;
vector<Attracti on*>::iterator p ;

public: //Public functions
~Handler();
void addAttraction(s tring name, int visitors);
void printAttraction s();

};

#endif

and in the Handler.cpp I have:

Handler.cpp - snippet:

bool operator<(const Attraction& a,const Attraction& b){
return a.visitors < b.visitors;
}

Here is the function that performs the sort after adding a value:

void Handler::addAtt raction(string name, int visitors){

Attraction *attr;
attr=new Attraction();

attr->name=name;
attr->visitors=visit ors;

attractions.pus h_back(attr);
sort(attraction s.begin(),attra ctions.end());

}

However, whatever I do, it will never use the overloaded < operator
for sorting. What am I doing wrong? If I add the overloaded function
in the header it starts complaining because it will also be inserted
into the main program which is confusing since I have a guard around
the header file.
I suspect the fundamental problem is that you are sorting pointers
rather than objects. In other words, std::sort works on the value_type
of the container, which in your case is Attraction*, not Attraction.

So, do you need to operator on the Attraction object polymorphically ?
If not, don't use pointers; just allocate it on the stack, and let
vector make a copy (assuming attractions is now of type
vector<Attracti on>:

void Handler::addAtt raction( const string& name, const int visitors )
{
const Attraction attr = { name, visitors };
attractions.pus h_back(attr);
sort(attraction s.begin(),attra ctions.end());
}

Note also that I changed the function parameters to const (see
http://www.parashift.com/c++-faq-lit...rrectness.html) and the
string to a reference so it doesn't make an additional copy (see
http://www.parashift.com/c++-faq-lite/references.html).

If you do need to use it polymorphically and to store it in a vector,
prefer smart pointers such as std::tr1::share d_ptr (aka
boost::shared_p tr) or one of the smart pointers found in this FAQ and
those following:

http://www.parashift.com/c++-faq-lit...html#faq-16.22

BTW, you could put just the function prototype for your operator< in
the header or you could declare it "inline" to get rid of the
duplication problem.

Cheers! --M

Mar 1 '07 #3
Frank wrote:

Victor and mlimber have addressed your main issue. I'd like to address
one other item.
Handler.h:

#ifndef H_HANDLER //Guard
#define H_HANDLER

#include <iostream>
#include <vector>
using namespace std;
Do *NOT* put "using namespace std;" into a header file. It can
seriously mess up other code. It should only go into non-header files,
after all include directives.

Mar 1 '07 #4
On 1 mrt, 17:35, red floyd <no.s...@here.d udewrote:
Frank wrote:

Victor and mlimber have addressed your main issue. I'd like to address
one other item.
Handler.h:
#ifndef H_HANDLER //Guard
#define H_HANDLER
#include <iostream>
#include <vector>
using namespace std;

Do *NOT* put "using namespace std;" into a header file. It can
seriously mess up other code. It should only go into non-header files,
after all include directives.

Thanks everyone for the quick response!
It works like a charm now,
Regards,
Frank

Mar 1 '07 #5
On Thu, 1 Mar 2007 10:56:53 -0500, "Victor Bazarov" wrote:
>Your operator< is defined for _objects_, but your vector is storing
_pointers_. Drop the 'new', drop the pointers, keep objects, and
everything will be fine.
Except that objects in the OO sense like Attraction, Handler, ...
usually are not copyable.
>You can declare/define a local Attraction object in 'addAttraction'
and then push_back it, the vector will make a copy.
That's the problem.

Best regards,
Roland Pibinger
Mar 1 '07 #6
Roland Pibinger wrote:
On Thu, 1 Mar 2007 10:56:53 -0500, "Victor Bazarov" wrote:
>Your operator< is defined for _objects_, but your vector is storing
_pointers_. Drop the 'new', drop the pointers, keep objects, and
everything will be fine.

Except that objects in the OO sense like Attraction, Handler, ...
usually are not copyable.
"Usually"? What in the world do you mean? See to original post for
clarification.
>You can declare/define a local Attraction object in 'addAttraction'
and then push_back it, the vector will make a copy.

That's the problem.
REALLY? Do you mean that the OP's Attraction object is non-copiable?
Could you please elaborate?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 1 '07 #7
On Mar 1, 2:31 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Roland Pibinger wrote:
On Thu, 1 Mar 2007 10:56:53 -0500, "Victor Bazarov" wrote:
Your operator< is defined for _objects_, but your vector is storing
_pointers_. Drop the 'new', drop the pointers, keep objects, and
everything will be fine.
Except that objects in the OO sense like Attraction, Handler, ...
usually are not copyable.

"Usually"? What in the world do you mean? See to original post for
clarification.
You can declare/define a local Attraction object in 'addAttraction'
and then push_back it, the vector will make a copy.
That's the problem.

REALLY? Do you mean that the OP's Attraction object is non-copiable?
Could you please elaborate?
Roland's just being an OO purist. Objects in his world are always
polymorphic, but in C++'s multiple paradigms, they are not. In this
case, I don't think the OP was intending to use pure OO anyway, so our
answers sufficed.

Cheers! --M

Mar 1 '07 #8
On Thu, 1 Mar 2007 14:31:38 -0500, "Victor Bazarov" wrote:
>Roland Pibinger wrote:
>On Thu, 1 Mar 2007 10:56:53 -0500, "Victor Bazarov" wrote:
>>You can declare/define a local Attraction object in 'addAttraction'
and then push_back it, the vector will make a copy.

That's the problem.

REALLY? Do you mean that the OP's Attraction object is non-copiable?
Could you please elaborate?
Objects (in the OO sense) are characterized by identity, state and
behavior. When you duplicate (copy) objects you get into trouble with
identity and state, e.g.

Account a1 (12345);
Account a2 = a1;
a1.deposit (100);
a2.withdraw (200);

What does it mean to copy the account with account number 12345? What
is the balance of this account now? To answer your question,
Attraction (whatever that exactly means in the example) is an object
(in the sense of OO) and should not be copied.

Best regards,
Roland Pibinger
Mar 2 '07 #9
On 1 Mar 2007 12:12:00 -0800, "mlimber" <ml*****@gmail. comwrote:
>Roland's just being an OO purist. Objects in his world are always
polymorphic, but in C++'s multiple paradigms, they are not.
So 'C++'s multiple paradigms' have changed the paradigms? C++ has
changed the meaning of object (OO) and polymorphism?
Mar 2 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1295
by: Tatu Portin | last post by:
1: #include <iostream> 2: 3: typedef struct { 4: double r; 5: double i; 6: } complex; .. .. .. 24: ostream & operator<< (ostream &str, const complex &a)
2
2474
by: franklini | last post by:
hello people i. can anybody help me, i dont know what is wrong with this class. it has something to do with the me trying to override the input output stream. if i dont override it, it works fine. i would forget overriding it but i have to do it because its a coursework. here is a simple version of the class #include <iostream> #include <string> #include <vector>
10
1659
by: pmatos | last post by:
Hi all, I have the following code: class test { public: test(const std::string *n) : name(n) {} virtual ~test() {} const std::string * getName() { return name; }
11
2490
by: gao_bolin | last post by:
I am facing the following scenario: I have a class 'A', that implements some concept C -- but we know this, not because A inherits from a virtual class 'C', but only because a trait tell us so: class A {}; template <typename T> struct Is_C { static const bool value = false;
5
2245
by: Bob Gregory | last post by:
Hi all, I'm utter C# newbie, do be gentle. VS2005 Express refuses point blank to install on my box, so I'm stuck with C# 1.0 unless someone can point me to a C#2.0 compiler elsewhere. I have an authentication system rigged up, which is working, but I'd like to be able to run a test like this <code>
1
2436
by: Suman | last post by:
Hello All, Given a structure: struct s { char *name; wchar_t *surname; }; I wish to define a friend function for the above struct: std::ostream& operator<<(std::ostream& out, const s& x);
2
2261
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include <iostream> #include <fstream> #include <sstream>
45
18904
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
10
1823
by: ozizus | last post by:
I overloaded operator << for STL map successfully: template <typename T1, typename T2ostream & operator << (ostream & o, map <T1,T2& m) { //code } the code works like a charm. Now, I want the same functionality for multimap. Since their interface is same for the problem at hand, I
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10081
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.