Reputation: 121
Anyone knows how to sort a char*
using std::sort()
STL function? In c++
If i use sort like sort(str.begin(),str.end());. An error is coming -'request for member begin and end in str, which is of non-char type 'char*'.
I know how to sort a string using std::sort()
in #include<algorithm>
Upvotes: 2
Views: 480
Reputation: 7034
You can sort char* strings, but you can't modify string literals, so you need to have the string as a char array to be able to modify it (including sort):
//this is a string literal that can't be modified
const char* string_literal = "this can't be modified";
// this is a char[] that is initialized from a string literal
char str1[] = { "can modify" };
//array can be converted to pointer to first element
char* str_ptr = str1;
//str1 can be directly passed to sort, i just added str_ptr to make the conversion explicit
std::sort(str_ptr, str_ptr + std::strlen(str_ptr));
//the method with std::begin only works for char[], doesn't work for char*
//this could be initialized with a string literal as in previous example
char str2[] = { 'c', 'a', 'n', ' ', 'm', 'o', 'd', 'i', 'f', 'y', '\0' };
//end -1 because we want to keep the last character in place (the end string null termination character)
std::sort(std::begin(str2), std::end(str2) - 1);
Upvotes: 1
Reputation: 96335
If you have a pointer to the beginning of a string, you can pass it directly to std::sort
as the first parameter.
Then the second parameter needs to be the pointer to end of the string. You can get it by adding string length to that pointer.
std::sort(ptr, ptr + std::strlen(ptr));
Upvotes: 5