2016-09-14 5 views
0

STLを使用して部分文字列を並べ替える方法はありますか?STLを使用して部分文字列を並べ替える

私はこれを行うことができます。

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

しかし、どのように任意のインデックスのイテレータを取得できますか?

EG-Iが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; 
} 
+1

word.begin()+ 2、word.begin()+ 4。サイズを確認することを忘れないでください。 – Danh

+1

次の字句順について 'std :: next_permutation'を見ることができます。 [デモ](https://ideone.com/M2Z5MT) – Jarod42

答えて

2

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

ありがとう!これは作品に見えます。私のコードはまだそれが何をすべきかをしていないようです。元の質問を編集しました。どうぞご覧ください。 – Metafity

関連する問題