Metafity Metafity - 1 year ago 101
C++ Question

Sort a substring using STL

Is there any way to sort a substring using STL?

I know I can do this.

std::string word="dcba";
std::sort(word.begin(), word.end());

But how do I obtain iterators for arbitrary indices?

Eg- If I wanted to sort from indices 2 to 4, "dcab"

Edit - This was needed for a function to generate the next lexicographical sequence from a given string.

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]) {
return true;
return false;

Answer Source

std::string uses random-access iterators, so you can simply add the indexes to the begin iterator:

std::string word="dcba";
std::sort(word.begin()+2, word.begin()+4);

Alternatively, you can use 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);

Alternatively, you can use std::next() (C++11 and later):

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download