Page 1 of 1

sorting a double Array using <algorithm>

Posted: Mon May 15, 2006 11:37 am
by Ankur Handa
I am facing problem in sorting a double array . Can somebody help me ?
This is the Code i wrote but its giving error

Code: Select all

#include<iostream>
#include<algorithm>
#include<stdlib.h>
using namespace std;
int Comparison(const char *s1 , const char *s2)
{
        if(strcmp(s1,s2)>1)
                return 1;
        else
                return 0;
}
int main(void)
{
        char *s[2];
        s[0] = "Ankur";
        s[1] = "Handa";
        sort(s,2,Comparison);
        for(int i=0;i<=1;i++)
                printf(" %s\n",s[i]);
        return 0;
}

The error is Coming out to be

Code: Select all

sortArrayofPointers.cpp: In function

Posted: Tue May 16, 2006 5:41 pm
by Dzhefri
Check out the usage of sort:

(copied from http://www.cppreference.com/cppalgorithm/sort.html):

Code: Select all

#include <algorithm>
  void sort( iterator start, iterator end );
  void sort( iterator start, iterator end, StrictWeakOrdering cmp );
So you need 2 or 3 arguments after sort, and the first 2 muts be iterators. (Do you already know about iterators, btw?) That doesn't match the arguments that you're passing to sort().

Posted: Wed May 17, 2006 8:05 am
by Moha
You sort an array of strings instead of doubles!

Posted: Wed May 17, 2006 4:28 pm
by chunyi81
If you meant to sort an array containing only 2 strings then there is no need to even use the sort function. You can just directly compare and both strings and swap the two strings if necessary. The phrase "double array" will make some people think you are trying to sort an array of double floating point numbers but in fact in your code you are sorting an array of two strings.