【发布时间】:2016-09-14 15:43:25
【问题描述】:
有没有办法使用 STL 对子字符串进行排序?
我知道我能做到。
std::string word="dcba";
std::sort(word.begin(), word.end());
但是如何获得任意索引的迭代器?
例如- 如果我想从索引 2 到 4 排序,“dcab”
编辑 - 这是函数从给定字符串生成下一个字典顺序所必需的。
bool nextLex(string s) {
for(int i=s.length()-1;i>=0;i--) {
for(int j=i-1;j>=0;j--) {
if(s[j]<s[i]) {
swap(s[i],s[j]);
sort(s.begin()+j,s.end());
cout<<s<<endl;
return true;
}
}
}
return false;
}
【问题讨论】:
-
word.begin()+2, word.begin()+4。不要忘记检查尺寸
-
您可以查看
std::next_permutation以获得下一个字典顺序。 Demo