参照渡しを使ってみる (C++)
競プロ
Published: 2020-05-23

確認環境

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

void f1(int *a) {
    for (int i = 0; i < 3; i++) {
        a[i] *= 2;
    }
}

void f2(vector<int> &a) {
    for (int i = 0; i < 3; i++) {
        a[i] *= a[i];
    }
}

int main() {
    int a[] {1, 2, 3};
    f1(a);

    vector<int> b = {1, 2, 3};
    f2(b);

    // 関数を通すと値が変わっている
    for (int i = 0; i < 3; i++) {
        cout << a[i] << " ";
    }
    cout << endl;

    for (int i = 0; i < 3; i++) {
        cout << b[i] << " ";
    }
    cout << endl;
}

出力結果

2 4 6
1 4 9

参考