P
PolkaHead
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(?, ?, SimplerPrintFunctor() );,
See the code below:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
class Element
{
public:
Element(std::string name)
: m_name(name)
{}
void printName() const
{
std::cout << m_name << std::endl;
}
private:
std::string m_name;
};
class PrintFunctor : public std::unary_function<std::vector<Element*>,
bool>
{
public:
void operator()(const std::vector<Element*>& vec) const
{
std::for_each( vec.begin(), vec.end(),
std::mem_fun(&Element:rintName) );
}
};
class SimplerPrintFunctor : public
std::unary_function<std::vector<Element*>, bool>
{
public:
void operator()(const Element* element) const
{
element->printName();
}
};
int main()
{
std::vector<std::vector<Element*> > myVec;
std::vector<Element*> tempVec;
tempVec.push_back(new Element("e1"));
tempVec.push_back(new Element("e2"));
myVec.push_back(tempVec);
for_each(myVec.begin(), myVec.end(), PrintFunctor() );
}
(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(?, ?, SimplerPrintFunctor() );,
See the code below:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
class Element
{
public:
Element(std::string name)
: m_name(name)
{}
void printName() const
{
std::cout << m_name << std::endl;
}
private:
std::string m_name;
};
class PrintFunctor : public std::unary_function<std::vector<Element*>,
bool>
{
public:
void operator()(const std::vector<Element*>& vec) const
{
std::for_each( vec.begin(), vec.end(),
std::mem_fun(&Element:rintName) );
}
};
class SimplerPrintFunctor : public
std::unary_function<std::vector<Element*>, bool>
{
public:
void operator()(const Element* element) const
{
element->printName();
}
};
int main()
{
std::vector<std::vector<Element*> > myVec;
std::vector<Element*> tempVec;
tempVec.push_back(new Element("e1"));
tempVec.push_back(new Element("e2"));
myVec.push_back(tempVec);
for_each(myVec.begin(), myVec.end(), PrintFunctor() );
}