[ create a new paste ] login | about

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

C++, pasted on Jun 20:
#include <stdlib.h>
#include <time.h>

#include <iostream>
#include <algorithm>
#include <numeric>
#include <iterator>

#include <locale>

struct summator
{
	template <typename T, size_t N>
	T operator()(const T (&arr)[N]) const
	{
		return std::accumulate(arr, arr + N, T());
	}
};

template <typename T, size_t Cols, size_t Rows>
T (&sum(const T (&m)[Cols][Rows], T (&arr)[Cols]))[Cols]
{
	std::transform(m, m + Cols, arr, summator());
	return arr;
}

struct rng
{
	int operator()() const
	{
		return rand() % 10;
	}
};

template <typename T, size_t Cols, size_t Rows>
T (&fill(T (&m)[Cols][Rows]))[Cols][Rows]
{
	std::generate(&m[0][0], &m[0][0] + Cols * Rows, rng());
	return m;
}

template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
	std::copy(arr, arr + N, std::ostream_iterator<T>(os, " "));
	return os;
}

template <typename T, size_t Cols, size_t Rows>
std::ostream& operator<<(std::ostream& os, const T (&m)[Cols][Rows])
{
	for (const T (*it)[Rows] = m; it != m + Cols; ++it)
		os << *it << std::endl;

	return os;
}

int main()
{
	srand((unsigned) time(NULL));
	setlocale(LC_ALL, "");

	int m[5][8] = {{0}};
	std::cout << fill(m) << std::endl;

	int result[5] = {0};
	std::cout << sum(m, result) << std::endl;

	return 0;
}


Output:
1
2
3
4
5
6
7
3 2 5 3 1 3 2 8 
9 0 0 2 1 7 0 6 
2 4 9 3 9 9 4 9 
0 9 0 4 9 2 1 2 
4 8 7 7 2 1 7 3 

27 25 49 27 39 


Create a new paste based on this one


Comments: