473,793 Members | 2,810 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
14 2090
On 2 Mar, 08:26, rpbg...@yahoo.c om (Roland Pibinger) wrote:
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?
struct Account{

double value;
Account(double value_in) :value(value_in ){}
Account(Account & other)
{
value = other.value;
other.value =0;
}

void deposit( double val)
{
value += val;
}
void withdraw(double val)
{
value -= val;
}
};

#include <iostream>
int main()
{
Account a1 (12345);

std::cout << a1.value <<'\n';

Account a2 = a1;
std::cout << a1.value <<'\n';

a1.deposit (100);
std::cout << a1.value <<'\n';

a2.withdraw (200);
}

output:

12345
0
100
I Am Joking of course :-) :-) :-)

Mar 2 '07 #11
On Mar 2, 3:36 am, rpbg...@yahoo.c om (Roland Pibinger) wrote:
On 1 Mar 2007 12:12:00 -0800, "mlimber" <mlim...@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?
C++ has not changed the meaning of polymorphism, but because of its
multi-paradigmatic nature, not every "object" is an OO object either.

struct B { virtual void f(); };

B b;
b.f(); // Will invoke B::f() directly
B& bref = b;
bref.f(); // Will invoke B::f() indirectly

In this example "b" is not being used polymorphically in the first
invocation of B::f(), but it is in the second.

Cheers! --M

Mar 2 '07 #12
Roland Pibinger wrote:
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?
You made a copy of the C++ object. I see nothing bad about it.
What
is the balance of this account now?
How the F should I know? Youi didn't explain any behaviour of the
'Account' class.
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.
You seem confused a bit...

'12345' has nothing to do with the identity of the object. &a1 and &a2
are the identities of the objects. '12345' is just a value that takes
part in the object's behaviour. Now, the "identity issue" can be seen
if you *pretend* that the operation

Accout &ra1 = a1;

is actually "making a copy". It isn't, of course, since &ra1 == &a1.

In the account example you gave, the actual bank account associated in
some way with 'a1' and 'a2' *objects* (instances of the 'Account' type)
is a separate "object" that has little to do with the program, and only
exists in the model, which apparently is not very well represented by
the 'Account' class (in terms of copying, obviously, using the terms of
what seems to be the model you're alluding to).

In "pure" OOP, according to you, no copy can be made. That doesn't
sound like a good thing. In the real world copies are made all the
time. Perhaps making a copy means different thing to different people
and your meaning is different from the C++'s one? The saying we use
in a situation like this is "don't push your own charter in someone
else's monastery". If you'd like the other monastery to adopt your
charter (or to amend its charter according to some of your views), you
might want to explain instead of attacking the monastery's principles
and values.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 2 '07 #13
On Fri, 2 Mar 2007 12:06:01 -0500, "Victor Bazarov" wrote:
>Roland Pibinger wrote:
>Account a1 (12345);
Account a2 = a1;
a1.deposit (100);
a2.withdraw (200);

What does it mean to copy the account with account number 12345?

You made a copy of the C++ object. I see nothing bad about it.
So there is no problem?
>What
is the balance of this account now?

How the F should I know? Youi didn't explain any behaviour of the
'Account' class.
So actually there is a problem! Why should copying need an
explanation?
>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.

You seem confused a bit...
The confusion is not on my side.
>'12345' has nothing to do with the identity of the object. &a1 and &a2
are the identities of the objects. '12345' is just a value that takes
part in the object's behaviour.
Right, in C++ object identity by default is established as address.
'Object IDs' are necessary e.g. when the object is stored in a
database (and the memory address is lost). But that doesn't affect my
example at all.
>Now, the "identity issue" can be seen
if you *pretend* that the operation

Accout &ra1 = a1;

is actually "making a copy". It isn't, of course, since &ra1 == &a1.
The example just shows what happens when you try to duplicate stateful
objects with identity. But ...
>In the account example you gave, the actual bank account associated in
some way with 'a1' and 'a2' *objects* (instances of the 'Account' type)
is a separate "object" that has little to do with the program, and only
exists in the model, which apparently is not very well represented by
the 'Account' class (in terms of copying, obviously, using the terms of
what seems to be the model you're alluding to).
You seem to confirm my example. It makes no sense to have 2 instances
of the same underlying "object".
>In "pure" OOP, according to you, no copy can be made. That doesn't
sound like a good thing.
Look at dedicated OO languages like Java. You can implement a
copy-constructor in Java but why should you duplicate an object?
>In the real world copies are made all the
time. Perhaps making a copy means different thing to different people
and your meaning is different from the C++'s one?
Copies of _values_ are made all the time but not of objects. You need
to distinguish between objects and values, see e.g.
http://www.two-sdg.demon.co.uk/curbr...luedIdioms.pdf
>The saying we use
in a situation like this is "don't push your own charter in someone
else's monastery". If you'd like the other monastery to adopt your
charter (or to amend its charter according to some of your views), you
might want to explain instead of attacking the monastery's principles
and values.
I don't have a 'charter' and use only vocabulary commonly applied in
software engineering. The downside of the 'multiparadigm' approach in
C++ is that one not only needs to understand multiple paradigms but
also know how to combine them in a reasonable way. Otherwise one will
tackle the problems with the wrong tools.

Best regards,
Roland Pibinger
Mar 2 '07 #14
Roland Pibinger wrote:
[..] The downside of the 'multiparadigm' approach in
C++ is that one not only needs to understand multiple paradigms but
also know how to combine them in a reasonable way. Otherwise one will
tackle the problems with the wrong tools.
No! You don't need to combine anything. There is no requirement
not to wear OO after Labor Day. There is no requirement to combine
any paradigms or do it in any "reasonable way". Any way that gets
you where you're going is good.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 3 '07 #15

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
2475
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
1662
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
2491
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
2440
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
2262
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
18908
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
9518
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
10212
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
10161
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,...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6777
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
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4112
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.