mercredi 8 février 2023

Proper way to assign lambda as a function argument [duplicate]

I've been writing a program that takes an array and returns a summary of elements that fit the condition. What am I doing wrong?

#include <iostream>
#include <array>
using namespace std;
template<typename arg>
float sum(float *arr, arg&& condition){
    int res=0;
    for(int i=0;i<sizeof(arr);i++) if(condition(arr[i])) res+=arr[i];
    return res;
}
int main(){

    // just array initialization
    int size;
    cout << "enter size: ";
    cin>>size;
    cout<< endl;
    float arr[size];
    for (int i=0;i<size;i++){
        arr[i]= float((rand() % 100))/100;
        cout << arr[i] << " ";
    }
    cout << sum(arr, [](auto&& val){ return val < 0.25 ;}) << endl; // i'm getting an error here
    
    return 0;
}

I've tried modifying Code Runner settings.json to work with c++11 but it didn't seem to fix the warning. I'm using VSCode and Code Runner. Error output:

warning: rvalue references are a C++11 extension [-Wc++11-extensions]
float sum(float *arr, arg&& condition){
                         ^
*.cpp:22:22: error: expected expression
    cout << sum(arr, [](auto&& val){ return val < 0.25 ;}) << endl;
                     ^
1 warning and 1 error generated.

Aucun commentaire:

Enregistrer un commentaire