C++ Libraries/Algorithm Overview

From Software Engineers Wiki
Jump to: navigation, search

std::accumulate()

Sum of the elements

http://en.cppreference.com/w/cpp/algorithm/accumulate

template<class InputIt, class T, class BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, 
             BinaryOperation op)
{
    for (; first != last; ++first) {
        init = op(init, *first);
    }
    return init;
}

std::inner_product()

Sum of inner products of elements from two containers.

http://en.cppreference.com/w/cpp/algorithm/inner_product

template<class InputIt1, class InputIt2,
         class T,
         class BinaryOperation1, class BinaryOperation2>
T inner_product(InputIt1 first1, InputIt1 last1,
                InputIt2 first2, T value,
                BinaryOperation1 op1
                BinaryOperation2 op2)
{
    while (first1 != last1) {
         value = op1(value, op2(*first1, *first2));
         ++first1;
         ++first2;
    }
    return value;
}

std::partial_sum()

Each output elements have partial sum of input elements.

http://www.cplusplus.com/reference/numeric/partial_sum/

template <class InputIterator, class OutputIterator>
   OutputIterator partial_sum (InputIterator first, InputIterator last,
                               OutputIterator result)
{
  if (first!=last) {
    typename iterator_traits<InputIterator>::value_type val = *first;
    *result = val;
    while (++first!=last) {
      val = val + *first;   // or: val = binary_op(val,*first)
      *++result = val;
    }
    ++result;
  }
  return result;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox