473,666 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

classes containing operator() for std::sort, and virtual functions

In the following code example, I define several Comparator classes
which contain different compare functions to use with std::sort. I
have a Sorter class that gets passed a Comparator and is supposed to
sort using the specific Comparator that's passed to it.

But it always uses the Comparator base class and not the derived class
that it is supposed to use, although the functions are virtual.

How can I make the code work? You might argue that a Sorter class is
not needed, but I want one because I have more data and operations
related to sorting that I would like to put there.

#include <iostream>
#include <vector>

class Comparator {
public:
virtual bool operator() (const int& i1, const int& i2) const {
return i1 < i2;
}
};

// would like to make it abstract base class, but that doesn't compile
class ReverseComparat or : public Comparator {
public:
virtual bool operator() (const int& i1, const int& i2) const {
return i2 < i1;
};
};

class Sorter {
public:
Sorter(std::vec tor<int>& v, Comparator& c){
sort(v.begin(), v.end(), c);
}
};

int main(int argc, char** argv){
std::vector<int v;
v.push_back(3);
v.push_back(1);
v.push_back(2);
ReverseComparat or c;
Sorter s(v, c);
for(std::vector <int>::const_it erator it = v.begin(); it != v.end(); +
+it){
std::cout << *it << std::endl; // prints 1,2,3, instead of 3,2,1
}
return EXIT_SUCCESS;
}
Dec 4 '07 #1
1 2463
On Dec 4, 3:48 am, Markus Dehmann <markus.dehm... @gmail.comwrote :
In the following code example, I define several Comparator
classes which contain different compare functions to use with
std::sort. I have a Sorter class that gets passed a Comparator
and is supposed to sort using the specific Comparator that's
passed to it.
But it always uses the Comparator base class and not the
derived class that it is supposed to use, although the
functions are virtual.
The standard library uses value semantics for its agents. Which
means slicing, and no virtual functions.
How can I make the code work?
You need an additional level of indirection. Perhaps the
letter/envelop idiom.
You might argue that a Sorter class is not needed, but I want
one because I have more data and operations related to sorting
that I would like to put there.
#include <iostream>
#include <vector>
class Comparator {
public:
virtual bool operator() (const int& i1, const int& i2) const {
return i1 < i2;
}
};
// would like to make it abstract base class, but that doesn't compile
class ReverseComparat or : public Comparator {
public:
virtual bool operator() (const int& i1, const int& i2) const {
return i2 < i1;
};
};
class Sorter {
public:
Sorter(std::vec tor<int>& v, Comparator& c){
sort(v.begin(), v.end(), c);
Here's the problem line. std::sort is a template. Template
type deduction uses the static type. (It could hardly use
anything else, since it must be resolved at compile time.) So
the type of the comparison object here is Comparator. std::sort
takes its argument by value, copying the argument you give it
into a value parameter. Of type Comparator, so slicing occurs.

There are several solutions, but first: I'd recommend making
base classes abstract whenever possible, just to catch this sort
of thing. Rather than implementing the function in Comparitor,
make it pure virtual, and provide a derived class with the
default implementation. If Comparitor is abstract here, you'll
get all sorts of nasty messages from the compiler, rather than a
sort program with different semantics than those you wanted.

The simplest work around would be to define a simple wrapper for
a pointer to a Comparator, which forwards the operator()() to
the pointed to object. Alternatively, the letter/envelop idiom
is the classical way of combining value semantics with
polymorphism (but it may be more than what is needed here).
}
};
--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Dec 4 '07 #2

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

Similar topics

6
2330
by: alexhong2001 | last post by:
Does "std::sort" work only with sequence containers, not associative containers at all? Among sequential containers, can it be used with "list", "queue" and other sequence containers besides "vector"? Are "istringstream" and "ostringstream" covered in the book, "STL Tutorial and Reference" (second edition) by D. Musser, et al.? Seems like I could not find any related topic in the book.
1
2352
by: Ravi | last post by:
I came across code which contains: std::sort<unsigned char*>((newAnswer.begin()+1),newAnswer.end()); with newAnswer defined as std::vector<unsigned char>& newAnswer However upon attempting to compile the above code I got the following errors (I am using g++ ver 3.3.1 on Cygwin)
4
3341
by: hall | last post by:
I accidently overloaded a static member function that I use as predicate in the std::sort() for a vector and ended up with a compiler error. Is this kind of overload not allowed for predicates and if so, why not? Shouldn the compiler be able to tell which of he overloaded functions to use? The second A::comp() is the one I accidently added and gives the error message (in Borland C++Builder 6) Unit1.cpp E2285 Could not find a match for
7
3539
by: Ireneusz SZCZESNIAK | last post by:
I want to sort a vector with the std::sort function. There are two functions: one with two arguments, the other with three arguments. I am using the one with three arguments. I noticed that there is a huge overhead of using this function, which comes from copying the function object, i.e., the object that compares the elements of the vector, which is passed to the function not by reference but by value. Now, at the end of this mail...
15
3328
by: Peter Olcott | last post by:
Does anyone know how to do this?
5
3899
by: fade | last post by:
Good afternoon, I need some advice on the following: I've got a class that has a member std::vector<CStringm_vFileName and a member CString m_path; The vector contains a bunch of filenames with no path included (no C:\...) eg: my_file2.jpg, my_file1.bmp, etc... and m_path stores the path, eg: C:\folder1 I want to sort this vector according to different criterion, such as
8
2482
by: valerij | last post by:
Yes, hi How to write "operator +" and "operator =" functions in a class with a defined constructor? The following code demonstrates that I don't really understand how to do it... I think it has something to do with the compiler calling the destructor twice. Could someone point out where I go wrong? P.S.: The error it gives is "Debug Assertion Failure ....." (at run time) P.P.S: Everything else works just fine (without the use of...
11
656
by: Jeff Schwab | last post by:
Would std::sort ever compare an object with itself? I'm not talking about two distinct, equal-valued objects, but rather this == &that. The container being sorted is a std::vector. I've never seen this, but a coworker says he is. NB: I can't post sample code that reproduces the issue, nor do I claim any bug in the STL implementation (GCC 3.4.2). I'm just hoping a definitive answer resides in one of the brains who frequent this group.
10
6247
by: ikarus | last post by:
Hello C++ Gurus! I'm comparing sorting algorithm for study goals. I've compared STL std::sort and hand-coded introsort on millions (tens of millions) of integers array sorting. It was tested on random, sorted, and sorted in reverse arrays. In all tests on such a huge arrays std::sort is faster by ~1/4 then my version. So it seems that it some call optimization. My 'hand coded' version is based on D. Musser's suggestions and on some...
0
8444
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
8356
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
8869
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
8781
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
8551
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
8639
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4198
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...
0
4368
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2771
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

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.