首页 > 解决方案 > 如何在 C++ 中进行拳击?

问题描述

我有一个以下程序,它无法编译我相信这是因为它试图在 int 即原始类型上执行 begin()、end()。也许,我需要一个对象类型。我在这里正确吗?我该如何解决这个问题,我想在这里使用 lambda。

#include <iostream>
#include <algorithm>

using namespace std;

int main(void) {

    int N, i;
    cin >> N;

    int numArray[N]; // Define an array of four integers

    // Get inputs for the array elements
    for (i=0;i<N; i++) {
        cin >> numArray[i];
    }

    int sum = 0;
    // Write here the logic to add these integers:


    for_each(begin(numArray), end(numArray), [&](int n){ sum += n; });

    cout << sum << endl;  // Print the sum

    return 0;
}

编译错误——

 main.cpp:22: error: no matching function for call to 'begin(int [N])'
         for_each(begin(numArray), end(numArray), [&](int n){ sum += n; });
                            ^

标签: c++11

解决方案


使用std::begin(numArray)std::end(numArray)


推荐阅读