sort

I need to sort a string, for example string s="A0,A2,A1,A3" where s is a input string, and the required output is "A0,A1,A2,A3". How do i do it? i tried using sort function but couldn't get the required result
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
string a[]={"A0","A2","A1","A3"};
sort (a,a+4);
for (int i=0;i<4;i++){
cout << a[i]<< endl;
}
return 0;
}
You need to get data to array of strings and than sort it


You can create an array of pointers and sort it. Then rewrite the original character array into the destination array. Here is the corresponding code block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	{
		char s[] = "A0,A2,A1,A3";
		char * p[] = { s, s + 3, s + 6, s + 9 };

		std::sort( std::begin( p ), std::end( p ),
			[]( char *a, char *b ) { return ( std::strncmp( a, b, 2 ) < 0 ); } );

		char t[sizeof( s )];
		char *q = t;

		std::for_each( std::begin( p ), std::end( p ),
			           [&]( char *a )
		               {
						   std::strncpy( q, a, 2 );
						   q += 2;
						   *q++ = ',';
		              } );
		*--q = '\0';
		std::cout << t << std::endl;
	}


I testes it and it works.
Thanks every one.
Topic archived. No new replies allowed.