【问题标题】:Sort a substring using STL使用 STL 对子字符串进行排序
【发布时间】: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

标签: c++ string stl


【解决方案1】:

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));

【讨论】:

  • 谢谢!这看起来很有效。尽管我的代码似乎仍然没有做它应该做的事情。我已经编辑了原始问题,您介意看一下吗?
猜你喜欢
  • 2020-09-11
  • 2012-11-26
  • 2020-03-07
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多