473,581 Members | 3,067 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overriding stl::sort()

The stl::sort() that comes with Dev Studio 6 is broken (it hits the
degenerate case in a common situation). I have a replacement.
I would like to globally do "using namespace std; except use my
sort()".

I'd heard you can do this within a namespace:

namespace Fixed
{
using namespace std;
using Replacement::so rt();
}
using namespace Fixed;

However I couldn't get anything along this lines to work.
Anyone know how to do this?

Stuart

Jul 23 '05 #1
7 2440
"Stuart" <sj*@igs.net> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com
The stl::sort() that comes with Dev Studio 6 is broken (it hits the
degenerate case in a common situation). I have a replacement.
I would like to globally do "using namespace std; except use my
sort()".

I'd heard you can do this within a namespace:

namespace Fixed
{
using namespace std;
using Replacement::so rt();
}
using namespace Fixed;

However I couldn't get anything along this lines to work.
Anyone know how to do this?

Stuart

From what I understand, using declarations (e.g., using Replacement::so rt)
can only trump using directives (e.g., using namespace std;) by virtue of
the rule that identifiers declared in an inner scope hide identifiers
declared in an enclosing scope.

Using *directives* aren't declarations at all, they just put the identifiers
of a namespace in the global namespace. Using declarations, by contrast, are
declarations *in the current scope* and so can hide identifiers from an
enclosing scope, including the global namespace.

Consider your code:
namespace Fixed
{
using namespace std;
using Replacement::so rt();
}
You should drop the () after sort. With this correction, the code means
that, within namespace Fixed, Replacement::so rt hides the sort from the
global namespace (i.e., std::sort). Thus if you define a function within
namespace Fixed that calls sort, you won't have a name clash, e.g.,

namespace Fixed
{
using namespace std;
using Replacement::so rt;
void foo(int *ptr, int size)
{
sort(ptr, ptr+size); // uses Replacement::so rt
}
}

Your code:
using namespace Fixed;


just dumps everything from namespace Fixed into the global namespace. Thus
Replacement::so rt joins std::sort in the global namespace and you have a
name clash in the global namespace. This isn't a problem if you are only
going to call foo subsequently, since there is only one foo. It is a problem
if you are going to call sort.

If you do need to call sort within a function (including the function
main() ) that is *not* defined within namespace Fixed, then you need to add
the using Replacement::so rt; declaration to *each* such function or else
explicitly qualify sort when you use it, e.g.,

#include <algorithm>
#include <iostream>

namespace Replacement
{
template<class T>
void sort(T itbegin, T itend)
{
std::cout << "new sort function\n";
}
}

using namespace std;

int main()
{
using Replacement::so rt;
int array[] = {4,6,3,8,1};
sort(array, array+5); // uses Replacement::so rt
}

Note
1. The Replacement::so rt declaration must be inside main() but it makes no
difference where using namespace std is.
2. I can't guarantee that your compiler is standard compliant in the way it
handles using directives/declarations.

--
John Carson

Jul 23 '05 #2
So does this mean my options are:

1. Touch every file that calls sort
2. Touch every file that calls something in std
3. Instead of doing
using namespace std;
in my global include file (yes I know some people think that's
just wrong, but it is convenient!) I should do:
using std::min;
using std::max;
.... (continue to enumerate everything we use)
using Replacement::so rt;

Isn't there an easier way to override one specific name?
(I'm inclined to do option 3)

Stuart

Jul 23 '05 #3
"Stuart MacMartin" <sj*@igs.net> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com
So does this mean my options are:

1. Touch every file that calls sort
2. Touch every file that calls something in std
3. Instead of doing
using namespace std;
in my global include file (yes I know some people think that's
just wrong
Almost everyone, from what I have observed.
, but it is convenient!)
I should do:
using std::min;
using std::max;
.... (continue to enumerate everything we use)
using Replacement::so rt;

Isn't there an easier way to override one specific name?
(I'm inclined to do option 3)


Well, since we have abandoned any pretence at scrupulous programming, you
could use a macro:

#include <algorithm>
#include <iostream>

namespace Replacement
{
template<class T>
void sort(T itbegin, T itend)
{
std::cout << "new sort function\n";
}
}

#define sort Replacement::so rt

using namespace std;

int main()
{
int array[] = {4,6,3,8,1};
sort(array, array+5); // uses Replacement::so rt
}

Personally, I would remove all using declarations/directives from the header
file and add them, where appropriate, in the .cpp files.

--
John Carson

Jul 23 '05 #4
"John Carson" <jc************ ****@netspace.n et.au> wrote in message
news:da******** **@otis.netspac e.net.au

Well, since we have abandoned any pretence at scrupulous programming,
you could use a macro:


I mention this for completeness. It is a horrible idea. In particular,
macros don't respect scoping rules, so any attempt to use the identifier
sort (say, as a member function) will cause sort to be replaced by
Replacement::so rt.

--
John Carson

Jul 23 '05 #5
Don't worry, I wasn't about to do that.

We introduced "using std;" to force using a standard min and max.
We wanted to be sure that any conflict in names was caught (and we
just hit another moving to a new redhat platform) rather than
inadvertently
using the wrong one - one that might not be what we expect. And yes
we found some that didn't do what std::min and max do (though I can't
recall the details) I can handle that case by doing "using std::min;
using std::max;" globally (and similarly any other routine where we
ALWAYS mean the std one).

Does it offend your sensibilities to decide globally that certain
routines are used? e.g. globally do using Replacement::so rt;

Stuart

Jul 23 '05 #6
Stuart MacMartin wrote:
So does this mean my options are:

1. Touch every file that calls sort
2. Touch every file that calls something in std
3. Instead of doing
using namespace std;
in my global include file (yes I know some people think that's
just wrong, but it is convenient!) I should do:
using std::min;
using std::max;
.... (continue to enumerate everything we use)
using Replacement::so rt;

Isn't there an easier way to override one specific name?
(I'm inclined to do option 3)


Edit your compiler's header files and comment out std::sort .
(Or is there a problem with std::min and std::max?)

Jul 23 '05 #7
"Stuart MacMartin" <sj*@igs.net> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com
Don't worry, I wasn't about to do that.

We introduced "using std;" to force using a standard min and max.
We wanted to be sure that any conflict in names was caught (and we
just hit another moving to a new redhat platform) rather than
inadvertently
using the wrong one - one that might not be what we expect. And yes
we found some that didn't do what std::min and max do (though I can't
recall the details) I can handle that case by doing "using std::min;
using std::max;" globally (and similarly any other routine where we
ALWAYS mean the std one).

Does it offend your sensibilities to decide globally that certain
routines are used? e.g. globally do using Replacement::so rt;

Stuart


A lot of the rationale for namespaces comes from using code from multiple
suppliers in the one project. You might decide that the global use of a
particular function is appropriate, but what happens if you use a third
party library that depends on using a different function? Putting something
in a header file so as to deliberately create a name clash where the wrong
function is used in some legacy code is a useful tactic, but that doesn't
mean you have to leave it there after the uses of the wrong function have
been identified. One perhaps non-obvious problem with putting using
directives / declarations in header files is that it means that program
behaviour may depend on the order in which headers are included, which is a
fragility that should be avoided if possible.

If your using directives/declarations only occur in a single header file and
if you manage to always include it first, then you have a situation in which
you just have a whole lot of identifiers in the global namespace throughout
your program. This needn't be a huge problem, particularly if you make
little use of third party libraries. After all, it is how programs were
written before namespaces became part of the language. If you have a large
project and it would be a lot of work to change it, then you might decide to
live with this. You do, however, give up some of the benefits of namespaces.

There are circumstances in which a less-than-ideal design makes economic
sense for an existing project, given the cost of change (and, for small
projects, the problems that arise from less-than-ideal design, if any, are
often small enough to be managed manually). That is a judgement for you to
make.

--
John Carson

Jul 23 '05 #8

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

Similar topics

6
5980
by: Aaron Broad | last post by:
I can't get STL sort to work for this little huffman encoding program i'm writing. I get a whole whack of errors eminating from the line that call sthe sort. They all look like the following error: main.cpp:44: instantiated from here /usr/include/c++/3.2.2/bits/stl_algo.h:2004: no match for ` std::_List_iterator<HuffmanNode,...
10
1719
by: Paul Schneider | last post by:
I want to sort a class derived from std::vector with STL sort.: template<typename T, typename fitParaType, typename fitResType> class Manipulator{ // shouldn't I now be able to access private members with // Compare? friend class Compare; public: ...
6
9988
by: Der Andere | last post by:
I have an array of pointers (to a class) which I want to have sorted. I have implemented the < operator for the class but I guess STL sort will sort the pointers according to _their_ values (the addresses). Or will it work as I intended? Do you know ways to circumvent the problem? Thanks, Matthias -- Für emails Anweisung in der Adresse...
5
7096
by: Lieven De Keyzer | last post by:
Is the STL sort() algorithm implemented genericly over all the containers or once for each container? And in which file is it implemented?
7
6961
by: yinglcs | last post by:
Hi, I have a function which calls stl sort(). I pass in a STL list of 'Rect' (my own class), like this: void sortListY(const list<Rect>& rectList) { sort(rectList.begin(), rectList.end()); // if I comment out this line, the program compiles fine.
1
3462
by: Varun Kacholia | last post by:
Hi, I have a question regarding SGI STL sort implementation: In case of equal elements, will they be output in the same order each time I sort? (I understand that it is not a stable sort, and by "same order" I mean "same order *each time I sort*"). Or is there a random number used in the splitter for qsort? Thanks
2
1717
by: thinktwice | last post by:
i wanna sort the elements stored in a vector, but my sort function needs be a little different from the standard one, i wanna the sort function accept 3 parameters. stl::sort(myvec.begin(), myvec.end(), mysortfunc); bool mysortfunc(elem1, elem2, anoter parameter) { //is it possible ?? }
3
2164
by: mweltin | last post by:
I have a derived class that extends a base class by adding a float member. The strange part is when I use the STL sort algorithm on a vector of derived classes, only hte float member is sorted. For example assume a vector containg three derived class objects called blah. blah { ... int one = 7 , int two = 5, int three =8 , float five = 1}...
5
4916
by: feverzsj | last post by:
STL sort() as an implementation of introsort, below is the code snippet from the gnu stl. template<typename _RandomAccessIterator, typename _Size> void __introsort_loop(_RandomAccessIterator __first, _RandomAccessIterator __last, _Size __depth_limit) { typedef typename iterator_traits<_RandomAccessIterator>::value_type
0
7860
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...
0
8139
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. ...
1
7890
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...
0
8166
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...
0
6546
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...
1
5667
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...
0
5357
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...
1
1398
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1127
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...

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.