Metafity Metafity - 2 months ago 21
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]) {
swap(s[i],s[j]);
sort(s.begin()+j,s.end());
cout<<s<<endl;
return true;
}
}
}
return false;
}

Answer

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

Or:

std::string word="dcba";
auto start = std::next(word.begin(), 2);
std::sort(start, std::next(start, 2));
Comments