// ForEach.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ctime>
struct FindMaxOfAll
{
public:
FindMaxOfAll() : maxOfAll(0) {}
void operator()(std::vector<int>& cont)
{
int max = *(std::max_element(cont.begin(), cont.end()));
if(max > maxOfAll) { maxOfAll = max; }
}
int getMaxOfAll() { return maxOfAll; }
private:
int maxOfAll;
};
int main()
{
// fill containers with data
srand (time(NULL));
std::vector<std::vector<int> > values2d(5); //create 10 vectors of integers, all empty
std::for_each(values2d.begin(), values2d.end(),
[](std::vector<int>& cont) { cont.resize(5); std::generate ( cont.begin(), cont.end(), rand); });
std::ostream_iterator<int> out_it (std::cout,", ");
std::for_each(values2d.begin(), values2d.end(),
[&](std::vector<int>& cont) { std::copy ( cont.begin(), cont.end(), out_it ); });
// Find the max of all
FindMaxOfAll maxOfAll = std::for_each(values2d.begin(), values2d.end(), FindMaxOfAll());
std::cout << "\n\nthe max of all is " << maxOfAll.getMaxOfAll() << std::endl;
return 0;
}
That is my answer. Mine is more verbose but also includes how I initialized the vectors. This is the one thing that I have figured out that for_each can be useful for since it can actually maintain and return the state of the functor which allows you to do something like accumulating information. Is it the best? Who knows? What is best? fastest? Fewest lines of code? easiest to understand? That is very subjective. Since the asker has 99k rep I thought maybe it isn't homework after all. It seems like a fun, quick challenge to see the different ways that people would solve it.