C++ STL の reverse()

C++ では、 逆行する() は、指定された範囲の要素内の要素の順序を逆にするために使用される組み込み関数です。この範囲には、ベクトルなどの STL コンテナーまたは配列を指定できます。

C++
   #include          using     namespace     std  ;   int     main  ()     {      vector   <  int  >     v     =     {  1       2       3       4       5  };      // Reversing the vector      reverse  (  v  .  begin  ()     v  .  end  ());      for     (  int     i     :     v  )     cout      < <     i      < <     ' '  ;      return     0  ;   }   

出力
5 4 3 2 1  

reverse() の構文

reverse() 関数は次のように定義されています。 ヘッダファイル。

逆行する (最初から最後まで);

パラメータ:

  • 初め : 範囲内の最初の要素への反復子。
  • 最後 : 範囲内の最後の要素の直後の理論上の要素へのイテレータ。

戻り値:

  • この関数は値を返しません。その場で範囲を反転します。

配列を反転する

以下の例は、 reverse() 関数を使用してさまざまなデータ コンテナを逆にする方法を示しています。

C++
   #include          using     namespace     std  ;   int     main  ()     {      int     arr  []     =     {  1       2       3       4       5  };      int     n     =     sizeof  (  arr  )     /     sizeof  (  arr  [  0  ]);      // Reverse the array arr      reverse  (  arr       arr     +     n  );      for     (  int     i     :     arr  )     cout      < <     i      < <     ' '  ;      return     0  ;   }   

出力
5 4 3 2 1  

文字列を反転する

C++
   #include          using     namespace     std  ;   int     main  ()     {      string     s     =     'abcd'  ;      // Reverse the string s      reverse  (  s  .  begin  ()     s  .  end  ());      cout      < <     s  ;      return     0  ;   }   

出力
dcba 

reverse() を使用してベクトルを左回転する

ベクトルの左回転 これは、 reverse() を 3 回使用することで実行できます。

C++
   #include          using     namespace     std  ;   int     main  ()     {      vector   <  int  >     v     =     {  1       3       6       2       9  };      int     n     =     v  .  size  ();      int     d     =     2  ;      // Left rotate the vector by d place      reverse  (  v  .  begin  ()     v  .  begin  ()     +     d  );      reverse  (  v  .  begin  ()     +     d       v  .  end  ());      reverse  (  v  .  begin  ()     v  .  end  ());      for     (  auto     i     :     v  )      cout      < <     i      < <     ' '  ;      return     0  ;   }   

出力
6 2 9 1 3  
クイズの作成