I was wondering if there's a way to traverse a two-dimensional vector
(vector of vectors) with a nested for_each call.
The code included traverses the "outer" vector with a for_each, than it
relies on the PrintFunctor to traverse the "inner" vector with another
for_each. Is it possible to nest the second for_each, so I don't have
to include a for_each in my function object.
Is it possible to do a:
for_each(myVec. begin(), myVec.end(),
for_each(?, ?, SimplerPrintFun ctor() );,
See the code below:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
class Element
{
public:
Element(std::st ring name)
: m_name(name)
{}
void printName() const
{
std::cout << m_name << std::endl;
}
private:
std::string m_name;
};
class PrintFunctor : public std::unary_func tion<std::vecto r<Element*>,
bool>
{
public:
void operator()(cons t std::vector<Ele ment*>& vec) const
{
std::for_each( vec.begin(), vec.end(),
std::mem_fun(&E lement::printNa me) );
}
};
class SimplerPrintFun ctor : public
std::unary_func tion<std::vecto r<Element*>, bool>
{
public:
void operator()(cons t Element* element) const
{
element->printName();
}
};
int main()
{
std::vector<std ::vector<Elemen t* myVec;
std::vector<Ele ment*tempVec;
tempVec.push_ba ck(new Element("e1"));
tempVec.push_ba ck(new Element("e2"));
myVec.push_back (tempVec);
for_each(myVec. begin(), myVec.end(), PrintFunctor() );
}