Home > Mobile >  int32_t and int64_t Conversion Issues
int32_t and int64_t Conversion Issues

Time:02-16

In the following line of code, positive is a vector of int32_t elements.

int32_t pos_accum = accumulate(positive.begin(), positive.end(), std::multiplies<int32_t>());

The compiler generates the following error that seems to make no sense:

No suitable conversion function from "std::multiplies<int32_t>" to "int32_t" exists

as well as

'initializing': cannot convert from '_Ty' to 'int32_t'

The ultimate goal is to store the answer in an int64_t, but attempts to static_cast<int64_t> the result ends up in similar errors.

Any idea what the problem is here?

CodePudding user response:

The signature of std::accumulate that accepts a binary operator is

template< class InputIt, class T, class BinaryOperation >
constexpr T accumulate( InputIt first, InputIt last, T init, BinaryOperation op );

You're missing the init argument, which represents the initial value of the accumulation. Try

accumulate(positive.begin(), positive.end(), 1, std::multiplies<int32_t>());
  • Related