how do i sort a string array in descending order.

I have tried to use the sort method in the algorithm in my program.
It compiles fine, however it does not seem to sort my array in descending order.

this is my array of string
string dataStore[100];

let`s the take values for example, 2,3,A,68,4,13,26

i am trying to sort in descending manner.
i have tried doing this

1
2
sort(dataStore,dataStore+100,greater<string>());
cout<<dataStore[0];


However, it does not show me the sorted values.

May i know what`s wrong with the code?
Thanks in advance! =)
Because dataStore[0] is only returning the first character in the string.

If you want the whole string, then just do this:
cout << dataStore;
Last edited on
If you want to show all the strings in the array you can use a loop.
1
2
3
4
for (int i = 0; i < 100; i++)
{
	cout << dataStore[i] << endl;
}
Last edited on
OH. My bad. I wasn't thinking. I thought it was a char array. So. Do what peter says, ignore my post.

Thanks peter!
Last edited on
Hi guys thanks for your help. I managed to solve it. I have another question, is the sort method applicable to variables. Can i sort float variables from a function call?
If you store the floats inside some kind of container you can sort them.
hi peter, what if i changed the float value to a string using stringstream and stored it inside an string array. Am i able to sort the values according to the float value which was changed to string?


edit: something like this

1
2
3
4
5
float civiIndex=getData.getCiviIndex();
stringstream convertIndex;
convertIndex<<civiIndex;
string index=convertIndex.str();
dataStore[i]+=index;


now the computed value will be computed and stored inside datastore.

i want to sort using index, is there a way to do this?
Last edited on
You could do it by passing a comparison function that takes two strings as arguments, converts them to float values and then returns the value from comparing the two float values, to std::sort.
Last edited on
correct me if i`m wrong. Should it be something like this


1
2
3
4
5
6
7
8
float sortFunction(float a, float b)
{

 //implementation using stringstream 
   to convert the string variables into float

 returns them
}


sort method sort(dataStore,dataStore+100,sortFunction());
If you are sorting strings the comparison function must take strings as argument. The return type should be bool.
so it should be

1
2
3
4
5
6
7
8
bool sortFunction(string a , string b)
{
  //implementation


  returns them

}
Yes that will work.

When passing std::string objects to functions it is often better to pass the strings by reference to avoid unnecessary copying.
bool sortFunction(const string& a , const string& b)
Last edited on
ok thanks alot.


then how do i pass the values in

should i pass them in using my get method or using my datastore array?

You can use it the same way you did before.
ok sure, thanks alot =)
Hi peter, can you show me an example?
I`m really lost
Topic archived. No new replies allowed.