std::prev, std::next を使ってみる (C++)
C++
Published: 2020-07-09

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {5, 3, 2, 9, 8};

    auto iter = v.begin();
    cout << "begin(): " << *iter << endl;
    iter = next(iter);
    cout << "begin() + next1回: " << *iter << endl;
    iter = next(iter);
    cout << "begin() + next2回: " << *iter << endl;

    iter = prev(iter);
    cout << "begin() + next2回 + prev1回: " << *iter << endl;

    // この指定だと2回進む
    iter++;
    iter += 1;
    cout << "begin() + next2回 + prev1回 + 2回進む " << *iter << endl;
}

出力結果

begin(): 5
begin() + next1回: 3
begin() + next2回: 2
begin() + next2回 + prev1回: 3
begin() + next2回 + prev1回 + 2回進む 9

参考