使用STL对子字符串排序
Sort a substring using STL
是否有任何方法使用STL对子字符串进行排序?
我知道我能做到。
std::string word="dcba";
std::sort(word.begin(), word.end());
但是我如何获得任意索引的迭代器呢?
例如-如果我想从索引2到4排序,"dcab"
Edit -从给定字符串生成下一个字典顺序的函数需要这个。
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;
}
std::string
使用随机访问迭代器,因此您可以简单地将索引添加到begin
迭代器:
std::string word="dcba";
std::sort(word.begin()+2, word.begin()+4);
或者,您可以使用std::advance()
:
std::string word="dcba";
std::string::iterator start = word.begin();
std::advance(start, 2);
std::string::iterator end = start;
std::advance(end, 2);
std::sort(start, end);
或者,您可以使用std::next()
(c++ 11及更高版本):
std::string word="dcba";
std::sort(std::next(word.begin(), 2), std::next(word.begin(), 4));
或:
std::string word="dcba";
auto start = std::next(word.begin(), 2);
std::sort(start, std::next(start, 2));
相关文章:
- 对字符串进行排序时,在c++中处理sort()
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 字符串上的合并排序上的 Seg 错误
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- 如何在数组 c++ 中对字符串进行排序
- 提高从排序字符串中获取字母顺序的顺序复杂性
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何对向量进行排序<浮点数,字符串>而不考虑字符串
- C ++中的字符串排序,也没有在第5个元素正确排序
- C++:使用 LSD 基数排序字符串排序崩溃
- C 样式的字符串排序与排序和 qsort
- 自定义字符串排序
- 编号和字符串排序Al
- 使用STL对子字符串排序
- 如何在c++中按字母顺序对标准输入字符串排序
- c++向量字符串排序不工作
- SQLite 的不区分大小写的 UTF-8 字符串排序规则 (C/C++)