我有一个Java函数
static int a2(int[] a)
{
int sumEven = 0;
int sumOdd = 0;
for (int i=0; i<a.length; i++)
{
if (a[i]%2 == 0)
sumEven += a[i];
else
sumOdd += a[i];
}
return sumOdd - sumEven;
}
我在 java 中从 main 中调用它
public static void main()
{
a2(new int[] {1});
a2(new int[] {1, 2});
a2(new int[] {1, 2, 3});
a2(new int[] {1, 2, 3, 4});
a2(new int[] {3, 3, 4, 4});
a2(new int[] {3, 2, 3, 4});
a2(new int[] {4, 1, 2, 3});
a2(new int[] {1, 1});
a2(new int[] {});
}
其中 a2 是函数,参数是数组。 我想在 C++ 中实现同样的事情,但我不能像在 Java 中那样将数组传递给函数。它给出了错误 [error]taking address of temporary array。
在c++中,我就是这样做的
f((int[4]) {1,2,3,4});
Giving error => [error]获取临时数组的地址。
如何实现?
最佳答案
使用 std::vector
而不是处理低级数组:
int a2( const std::vector<int> &v )
{
return std::accumulate( v.begin(), v.end(), 0, []( int a, int b ) {
return a + ( b % 2 ? b : -b );
} );
}
int main()
{
a2( { 1, 2, 3 } );
}
关于c++ - [错误]在 C++ 中获取临时数组的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46689371/