accumulate objects

This is a discussion on accumulate objects within the C++ Programming forums, part of the General Programming Boards category; I'm trying to use std::accumulate to multiply objects but can't get it done. I get the error "cannot convert Acc ...

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    201

    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>()));
    }

  2. #2
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    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
    Posts
    201
    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, 08: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, 11:10 PM
  4. chain of objects within pop framework help needed
    By Davey in forum C++ Programming
    Replies: 0
    Last Post: 04-15-2004, 11:01 AM
  5. array of objects?
    By *~*~*~* in forum C++ Programming
    Replies: 4
    Last Post: 05-31-2003, 06:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21