使用STL对子字符串排序

Sort a substring using STL

本文关键字:字符串 排序 STL 使用      更新时间:2023-10-16

是否有任何方法使用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));