I saw a topic today about summing up the contents of an array... given that I was away on a programming break for so long, I decided to do some adventure and do it in other ways so that I can practice on what I had learned before.
Here's what I came up with:
Hmm, why not make it generic by using template?
Now it works for all types that have operator+= defined for them.
Maybe it's weird/unnecessary or cutting a hair with chainsaw, but for me, it was a good adventure :)
Here's what I came up with:
#include <iostream> #include <algorithm> using namespace std; class sum { int *_p; public: sum(int *a): _p(a) {} //constructor, a pointer must be given to initialize _p //overloaded operator() makes this class a function object void operator()(const int& a) { *_p += a; //add a to the total sum, which is pointed to by _p } }; int main() { int s=0; int array[] = {1,2,3,4}; //array to sum for_each(array, array+4, sum(&s)); cout<<"Sum: "<<s<<endl; return 0; }
Hmm, why not make it generic by using template?
template <typename T> class sum { T *_p; public: sum(T *a): _p(a) {} //constructor, a pointer must be given to initialize _p //overloaded operator() makes this class a function object void operator()(const T& a) { *_p += a; //add a to the total sum, which is pointed to by _p } }; int main() { int s=0; int array[] = {1,2,3,4}; //array to sum for_each(array, array+4, sum<int>(&s)); cout<<"Sum: "<<s<<endl; return 0; }
Now it works for all types that have operator+= defined for them.
Maybe it's weird/unnecessary or cutting a hair with chainsaw, but for me, it was a good adventure :)
2 Comments On This Entry
Page 1 of 1

ishkabible
12 November 2012 - 03:23 PM
there is actually an accumulate function in <numeric> that allows this. rather than requiring += it requires + and = with. with move semantics this is just as efficient as += too.
Page 1 of 1
← April 2021 →
S | M | T | W | T | F | S |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 |
Tags
Recent Entries
My Blog Links
Recent Comments
Search My Blog
2 user(s) viewing
2 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)