Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::accumulate example 2: summing a std::vector of a custom class using a C++11 lambda expression

 

std::accumulate example 2: summing a std::vector of a custom class using a C++11 lambda expression is a std::accumulate example to sum a std::vector of a custom class using a C++11 lambda expression.

 

 

 

 

 

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppAccumulateExample2.pro

 

QMAKE_CXXFLAGS += -std=c++11
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

#include <cassert>
#include <vector>
#include <numeric>

struct MyClass
{
  MyClass(const int x = 0) : m_x(x) {}
  int Get() const { return m_x; }
  private:
  int m_x;
};

int main()
{
  //Create a std::vector
  std::vector<MyClass> v;
  for (int i=0; i!=10; ++i) { v.push_back(MyClass(i)); }

  //Sum the std::vector using a C++11 lambda expression
  const int sum
    = std::accumulate(
      v.begin(),
      v.end(),
      0, // '0' is the initial value
      [](const int sum, const MyClass& my_class)
      {
        return sum + my_class.Get();
      }
    );

  //Assume std::accumulate works correctly
  assert(sum == 45);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml