문자열이있는 경우 문자를 정렬하는 기능이 내장되어 있습니까? 아니면 직접 작성해야합니까?
예를 들면 :
string word = "dabc";
다음과 같이 변경하고 싶습니다.
string sortedWord = "abcd";
아마도 char을 사용하는 것이 더 나은 옵션일까요? C ++에서 어떻게할까요?
문자열이있는 경우 문자를 정렬하는 기능이 내장되어 있습니까? 아니면 직접 작성해야합니까?
예를 들면 :
string word = "dabc";
다음과 같이 변경하고 싶습니다.
string sortedWord = "abcd";
아마도 char을 사용하는 것이 더 나은 옵션일까요? C ++에서 어떻게할까요?
답변:
표준 라이브러리의 헤더에 정렬 알고리즘 이 있습니다 <algorithm>. 제자리에 정렬되므로 다음을 수행하면 원래 단어가 정렬됩니다.
std::sort(word.begin(), word.end());
원본을 잃어 버리지 않으려면 먼저 사본을 만드십시오.
std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
std::sort은 기본적으로 알파벳 내림차순으로 정렬합니다. 그 치죠하는 것은 사소한 오타 그리고 당신이 원하는 드 의 버전 사용 순서를 구김 std::sort이가 소요 Compare세 번째 인수로하고 공급하는 std::greater대신 기본으로 std::less. 기본적으로 유형을 std::string사용 char하므로 예를 들어 std::sort(sortedWord.begin(), sortedWord.end(), std::greater<char>());— 원래 질문에서 "abcd"가 아닌 "dcba"의 결과를 제공합니다.
C ++ 의 표준 템플릿 라이브러리 인 헤더 파일에있는 sort함수 를 포함시켜야 합니다 .algorithm
사용법 : std :: sort (str.begin (), str.end ());
#include <iostream>
#include <algorithm> // this header is required for std::sort to work
int main()
{
std::string s = "dacb";
std::sort(s.begin(), s.end());
std::cout << s << std::endl;
return 0;
}
산출:
abcd
std::sort?