c++ - [错误]在 C++ 中获取临时数组的地址?

标签 c++

我有一个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 } );
}

live example

关于c++ - [错误]在 C++ 中获取临时数组的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46689371/

相关文章:

c++ - GLSL着色器即使没有明显的错误也不会编译

c++ - 为什么 ExposureCompensator 结果给出黑色图像?

c++ - boost fast_pool_allocator 有时会请求大量分配

c++ - 是否保证 std::vector 默认构造不会调用 new?

c++ - 当从 NSMutableString 中删除 UTF8 表情符号字符时,到 std::string 的转换失败

c++ - 高斯约尔消元法

c++ - C++ 的跨平台 sleep 功能

c++ - Process Explorer 使用哪个 winapi 函数来挂起进程?

javascript - C++与JS程序共享内存

c++ - 在不使用全局变量的情况下从主范围更改函数中的局部变量