どうも、ちょげ(@chogetarou)です。
for_eachを使ってVectorを後ろからループする方法を紹介します。
方法

for_eachを使ってVectorを逆順でループするには、rbegin()とrend()を使います。
まず、for_eachを呼び出します。
次に、for_eachの第1引数にVectorから呼び出したrbegin()、第2引数にVectorから呼び出したrend()を指定します。
for_eachの第3引数に、引数1つの関数を指定します。
関数の{}内に、ループ処理を指定します。
(関数の引数で、Vectorの要素を取得)
//T = vectorの要素の型, myVec = 対象のvector
for_each(myVec.rbegin(),
myVec.rend(),
[] (T x) {
//ループ処理
//引数で要素を取得
});
上記のfor_eachは、Vectorを逆順でループします。
https://cplusplus.com/reference/vector/vector/rbegin/
https://cplusplus.com/reference/vector/vector/rend/
使用例
#include <iostream>
#include <vector>
using namespace std;
int main(void){
vector<int> nums = { 1, 2, 3, 4, 5, 6 };
for_each(nums.rbegin(),
nums.rend(),
[] (int x) {
cout << x << endl;
});
return 0;
}
出力:
6
5
4
3
2
1
コメント