c++ - How to summarize the elements of std::set -
i'm trying find sum of elements in set , wondering ways find it. built 2 classes, 1 called customer , 1 called item, want write function calculate total payment customer needs pay products listed in std::set type item. here decleration of set:
set<item> _items;
the class item:
private: string _name; string _serialnumber; //consists of 5 numbers int _count=0; //default 1, can never less 1! double _unitprice; //always bigger 0!
function in class item summarize price of item:
double item :: totalprice() const { return _count*_unitprice; }
here function i'm trying write sum of elements:
#include <numeric> #include "customer.h" double customer::totalsum() const { double sum = std::accumulate(_items.begin(), _items.end(), 0.0); return sum; }
but error: error c2893: failed specialize function template 'unknown-type std::plus<void>::operator ()(_ty1 &&,_ty2 &&) const'
improtant note: class customer includes header of item.
edit: added information class item.
assuming item
this:
struct item { double price; };
then can use following:
auto add_item_price = [](double sum, const item& item) { return sum + item.price; }; double sum = std::accumulate(_items.begin(), _items.end(), 0.0, add_item_price);
explanation:
std::accumulate
lets provide function/functor accumulation. code i've posted uses lambda function accumulation. if aren't using c++11, can use regular function instead of lambda function.
avoid overloading operator+
item
. adding 2 item
s doesn't make sense.
Comments
Post a Comment