[ create a new paste ] login | about

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

fisherro - C++, pasted on Aug 23:
//http://bulldozer00.com/2015/08/20/easier-to-use-and-more-expressive/
//A third C++03 solution

//This is not intended as a criticism of the article.
//It is just an example of an additional solution.

//Why bother clearing the inner vectors if you are going to then clear the outer vector?
//Well, it is just an example...let’s not miss the point.
//Still, my function assumes you have a reason for clearing just the inner vectors and leaves the outer vector intact.

//IMHO, this solution is not as good as the ranged-for solution,
//but it is better than all the others.
//Although it is less general.
//If you need to do something more complex than v.clear(),
//this approach could get very ugly in C++03.

#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
#include <cstdlib>
#include <numeric>
#include <iostream>

class MyClass {
	std::vector< std::vector<double> > _vecVecDouble;
public:
	//This is the third C++03 solution:
	void clear_members()
	{
		std::for_each(_vecVecDouble.begin(), _vecVecDouble.end(), std::mem_fun_ref(&std::vector<double>::clear));
	}
	
	//Test the solution.
	void test()
	{
		std::generate_n(std::back_inserter(_vecVecDouble), 10, &generate_vec);
		std::cout << count() << '\n';
		clear_members();
		std::cout << count() << '\n';
	}
	
	//For testing: Create a vector with 10 random doubles.
	static std::vector<double> generate_vec()
	{
		std::vector<double> v;
		std::generate_n(std::back_inserter(v), 10, &std::rand);
		return v;
	}
	
	//For testing: Count and sum the elements of the inner vectors.
	size_t count()
	{
		std::vector<size_t> sizes(_vecVecDouble.size(), 0);
		std::transform(_vecVecDouble.begin(), _vecVecDouble.end(), sizes.begin(), std::mem_fun_ref(&std::vector<double>::size));
		return std::accumulate(sizes.begin(), sizes.end(), static_cast<size_t>(0), std::plus<size_t>());
	}
};

int main()
{
	MyClass mc;
	mc.test();
}


Output:
1
2
100
0


Create a new paste based on this one


Comments: