C++ では、for-each ステートメントで参照変数を使用できます。たとえばfor (int &e : vec)
、 where&e
は の値への参照ですe
。これにより、for-each ループで対話する要素の値を変更できます。Javaに同等の構造はありますか?
C++ の for-each ループで参照変数を使用する方法の例を次に示します。
#include <iostream>
#include <vector>
int main()
{
// Declare a vector with 10 elements and initialize their value to 0
std::vector<int> vec (10, 0);
// e is a reference to the value of the current index of vec
for (int &e : vec)
e = 1;
// e is a copy of the value of the current index of vec
for (int e : vec)
std::cout << e << " ";
return 0;
}
参照演算子 が最初のループで使用されなかった場合、 1 への割り当ては、 の現在の要素のコピー (参照ではない) である&
変数に対してのみ行われます。つまり、ベクトルから読み取るだけでなく、また、for-each ループでベクトルに書き込みます。e
vec
&
たとえば、次の Java コードは元の配列を変更せず、単にコピーを変更します。
public class test {
public static void main(String[] args) {
test Test = new test();
int[] arr = new int[10];
for (int e : arr) // Does not write to arr
e = 1;
for(int e : arr)
System.out.print(e + " ");
}
}