[ create a new paste ] login | about

Link: http://codepad.org/gdmNx2Y0    [ raw code | output | fork ]

pyrtsa_ - C++, pasted on Oct 17:
#include <vector>    // std::vector
#include <iostream>  // std::cout
#include <algorithm> // std::for_each

// a function object calculating the sum of floats
struct sum {
    float s;
    sum() : s(0) {}
    void operator()(float f) { s += f; }
    float get() const { return s; }
};

int main() {

    unsigned size = 10; // "dynamic" size
    std::vector<float> a(size); // dynamic allocation!

    for (unsigned i=0; i<a.size(); ++i) // a loop on indices
        a[i] = 1.0f + 2*i; // assign 1, 3, 5, 7, 9, ... to a[i]

    // a "loop" on iterators (a.begin(), a.end())
    sum s = std::for_each(a.begin(), a.end(), sum()); // calculate sum over a

    std::cout << "Sum over the " << a.size() << " elements of a: " << s.get() << std::endl;
    
} // a is destroyed (freed) here!


Output:
1
Sum over the 10 elements of a: 100


Create a new paste based on this one


Comments: