-
accumulate objects
I'm trying to use std::accumulate to multiply objects but can't get it done. I get the error "cannot convert Acc to int" in accumulate (BCB5). Anybody knows what's wrong?
Code:
struct Acc
{
Acc(int x) : x(x) {}
friend int operator*(const Acc& lhs, const Acc& rhs)
{ return lhs.x * rhs.x; }
int x;
};
int main()
{
Acc acc[] = { { 1 }, { 2 }, { 3 } };
std::cout <<
std::accumulate(
acc,
acc + sizeof acc / sizeof *acc,
1,
std::multiplies<Acc>()));
}
-
Your return type is int but you are returning... I don't even know what you're returning... You're given memory address of to structures (pointers, in effect), and then multiplying them together. You're multiplying the memory addresses together, not the values they point to. You should be using the -> operator. And I'm not even sure you're doing that correctly...
If you are using C++, classes would be a lot better for this application.
-
I see what I did wrong now.
1. the return value is an Acc instance
2. the "initial" parameter must be an Acc object, comp;iler took it as an int of course
Acc acc = std::accumulate(acc, acc + sizeof acc / sizeof *acc,
Acc(1), std::multiplies<Acc>()));
std::cout << acc.x << std::endl;
The iterators are correct, you can treat any pointer as an iterator, I always use C like code like this in small test programs.