Thread: accumulate objects

  1. #1
    Registered User
    Join Date
    Jun 2004

    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?

    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 <<    
        acc + sizeof acc / sizeof *acc, 

  2. #2
    Super Moderator
    Join Date
    Sep 2001
    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.

  3. #3
    Registered User
    Join Date
    Jun 2004
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Global objects and exceptions
    By drrngrvy in forum C++ Programming
    Replies: 1
    Last Post: 09-29-2006, 07:37 AM
  2. Replies: 60
    Last Post: 12-20-2005, 11:36 PM
  3. Question about cout an stack object?
    By joenching in forum C++ Programming
    Replies: 8
    Last Post: 05-08-2005, 10:10 PM
  4. chain of objects within pop framework help needed
    By Davey in forum C++ Programming
    Replies: 0
    Last Post: 04-15-2004, 10:01 AM
  5. array of objects?
    By *~*~*~* in forum C++ Programming
    Replies: 4
    Last Post: 05-31-2003, 05:57 PM