Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::accumulate won't' peform sum of elements with std::plus functor

I have a class which contains an integer among some other things:

class Foo
{
public:
    Foo() = default;
    Foo(int x)
        :
        x(x)
    {}
    int operator+(const Foo& rhs)
    {
        return x + rhs.x;
    }
private:
    int x;
    float whatever = 0.0f;
};

I also have a vector of these objects:

std::vector<Foo> foos{1, 2, 3, 4};

now, what I wanted to do was to use std::accumulate with the std::plus functor (or maybe some other STL function) to sum the X values of all elements in the vector, here’s what I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int sum = std::accumulate(foos.begin(), foos.end(), 0, std::plus<int>{});

But i’m getting a compiler error

Error C2440: "’initializing’ : cannot convert from ‘type1’ to ‘type2’
‘conversion’ : cannot convert from ‘type1’ to ‘type2’"

what am i doing wrong, how do I go about fixing this?

>Solution :

You are trying to add an int and a Foo with a function that takes two Foos.

You could use a function that adds int to Foo:

// in Foo
friend int operator+(int lhs, const Foo& rhs)
{
    return lhs + rhs.x;
}

Or you could use a function that adds two Foos

// in Foo
Foo operator+(const Foo& rhs)
{
    return { x + rhs.x };
}

// in main
Foo sum = std::accumulate(foos.begin(), foos.end(), Foo(0), std::plus<Foo>{});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading