Subscribe to Anarion's Blog        RSS Feed
-----

A Little Fun With C++

Icon 2 Comments
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:
#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 Icon

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.
1

Anarion Icon

12 November 2012 - 10:26 PM

ishkabible, on 13 November 2012 - 01:53 AM, said:

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.

I see... Didn't know about this function. Have to try it today when I get home. Thanks!
0
Page 1 of 1

July 2014

S M T W T F S
  12345
6789101112
13141516171819
20212223242526
272829 30 31  

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)