Container function



  • I tried to make accumulate the same function as std. Tell me how to fix it, please.

    template <typename T, typename T1>
    T1 accumulate(T begin, T end, T1 startvalue, function<T1(T1,T1)> a=
        [](T1 a,T1 b){return a+b;})
    {
    
    for (auto i = begin; i != end; i++)
    {
        startvalue = a(startvalue, *i);
    }
    return startvalue;
    

    }
    int main()
    {
    vector<int> v{ 2,3,1,234,685,246,76,5658,5657 };

    auto a = accumulate(v.begin(), v.end(), 1, [](int a, int b) {return a * b; });
    cout&lt;&lt;a;
    return 0;
    

    }



  • No need to typify the argument. a specific type. Typize it in the same way as all the other arguments.

    You'll be able to:

    #include <functional>
    

    // Если пользователь указал собственный бинарный оператор, используем его
    template <typename T, typename T1, typename BinaryOperation>
    T1 accumulate(T begin, T end, T1 startvalue, BinaryOperation a)
    {

    for (auto i = begin; i != end; i++)
    {
        startvalue = a(startvalue, *i);
    }
    return startvalue;
    

    }

    // Если же нет - используем оператор сложения
    template <typename T, typename T1>
    T1 accumulate(T begin, T end, T1 startvalue)
    {
    return accumulate(begin, end, startvalue, std::plus<>{});
    }

    You're also in charge. main the type intwhich makes it incorrect. To avoid this, you should use instead of a type int Type capable of absorbing the performance of the function:

    int main() {
    // ...
    auto a = accumulate(v.begin(), v.end(), 1ll, [](long long a, long long b) {return a * b; });
    // ...
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2