Hello ladies and gents,

I wanted to ask if this piece of code can be written differently then the way I did:

template <class V>

void sequence3(V &a, V &b, V &c)
{
	V w;

	while (a > b || b > c)
	{
		if (a > b){w = b; b = a; a = w;}
		if (b > c){w = c; c = b; b = w;}
		if (a > c){w = a; a = c; c = w;}
	}
}

Sure it can be written differently. What's the goal of the function?

Hi Narue,

The idea is sort three numbers/strings and sort them beginning with the smallest number or sort them alphabetically!

How about this:

#include <algorithm>

using namespace std;

template <typename T>
T& rmin ( T& a, T& b ) { return a < b ? a : b; }

template <typename T>
T& rmax ( T& a, T& b ) { return a > b ? a : b; }

template <typename T>
void order ( T& a, T& b, T& c )
{
  swap ( a, rmin ( a, rmin ( b, c ) ) );
  swap ( c, rmax ( a, rmax ( b, c ) ) );
}

Thanks for the example Narue, I was thinking about something simpler :lol:

Could you explain the reasons why you would prefer the way you wrote it, over mine please.

I understand that by using 'swap' , you don't have to make sure that your calculations are correctly written.

Seeing as you can use swap, isn't there a possibility to use sort? Something like this for instance?

#include <algorithm>

template <typename T>

void order ( T& a, T& b, T& c )
{
  sort ( a,  b, c);
}

I tried it like this, doesn't work :confused:

>I was thinking about something simpler
The simplest algorithm you can do for this is find the minimum value and place it in a, the maximum value, place it in c, and the remaining value goes in b. You can do it manually of course using a long chains of conditional statements, but it's easier to delegate to swap and suitably defined min/max routines.

>Could you explain the reasons why you would prefer the way you wrote it, over mine please.
You may not believe me, but my version is actually simpler than yours. ;)

>Seeing as you can use swap, isn't there a possibility to use sort?
Not if a, b, and c are all distinct objects. sort only works on a sequence, so you would need an array, a vector, or something similar for sort to work.

>> You may not believe me, but my version is actually simpler than yours.
:lol: I knew you would say this.

Well, thanks for the example and additional info Narue ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.