排序字符的C + +字符串
如果我有一个字符串是否有一个内置函数来排序字符或我会写我自己的?排序字符的C + +字符串
例如:
string word = "dabc";
我想改变它,以便:
string sortedWord = "abcd";
也许使用字符是一个更好的选择?我将如何在C++中执行此操作?
有一个在标准库a sorting algorithm,在报头中<algorithm>
。它排序,所以如果你做了以下,你的原始单词将被分类。
std::sort(word.begin(), word.end());
如果您不想丢失原件,请先复印一份。
std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
谢谢,我现在觉得很蠢,太多的PHP ... – gprime 2012-02-02 06:28:37
如果我们想让字符串按递增顺序排序呢? – madhuspot 2017-06-16 14:09:33
默认情况下,@madhuspot'std :: sort'按字母顺序递增排序。假设这是一个小错字,并且你想要压缩命令,可以使用'std :: sort'版本,它将'Compare'作为它的第三个参数,并提供'std :: greater'而不是默认的'std :: less'。 'std :: string'默认使用'char'类型,例如'std :: sort(sortedWord.begin(),sortedWord)。end(),std :: greater
你必须包括sort
函数,它是在algorithm
头文件是在C++ standard template library。
用法: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;
}
OUTPUT:
abcd
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
如何将在内部执行,请解释逻辑
我不理解你的评论“如何执行内部请解释逻辑”。 – 2017-11-17 10:39:34
什么'性病:: sort'? – dreamlax 2012-02-02 05:21:38
请注意,任何种类的基于幼稚字符值的排序都会以UTF-8为基础 - 取决于您想要考虑语言环境的字符串。 – 2017-11-17 10:44:06