473,399 Members | 3,401 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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 ReverseComparator : public Comparator {
public:
virtual bool operator() (const int& i1, const int& i2) const {
return i2 < i1;
};
};

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

int main(int argc, char** argv){
std::vector<intv;
v.push_back(3);
v.push_back(1);
v.push_back(2);
ReverseComparator c;
Sorter s(v, c);
for(std::vector<int>::const_iterator 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 2438
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 ReverseComparator : public Comparator {
public:
virtual bool operator() (const int& i1, const int& i2) const {
return i2 < i1;
};
};
class Sorter {
public:
Sorter(std::vector<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 objektorientierter Datenverarbeitung
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
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...
1
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...
4
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...
7
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...
15
by: Peter Olcott | last post by:
Does anyone know how to do this?
5
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...
8
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...
11
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...
10
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.