473,387 Members | 1,423 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Using for_each with a vector of vectors

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::printName) );
}
};

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() );

}

Nov 28 '06 #1
3 2839
PolkaHead wrote:
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() );,
If you templatize your 'SimplePrintFunctor', something like

template<class T>
void SimplePrintFunctor(T const& t)
{
t.printName();
}

template<class T>
void SimplePrintFunctor(std::vector<Tconst& vt)
{
for_each(vt.begin(), vt.end(), SimplePrintFunctor);
}

, it should work nicely for any nestedness of vectors. After that
you just do

SimplePrintFunctor(myvector);
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 28 '06 #2
Is there a way to do it with a Functor that only acts on one element
and not a whole vector. I was trying to avoid putting a for_each or
any loop in the SimplePrintFunctor...
Victor Bazarov wrote:
PolkaHead wrote:
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() );,

If you templatize your 'SimplePrintFunctor', something like

template<class T>
void SimplePrintFunctor(T const& t)
{
t.printName();
}

template<class T>
void SimplePrintFunctor(std::vector<Tconst& vt)
{
for_each(vt.begin(), vt.end(), SimplePrintFunctor);
}

, it should work nicely for any nestedness of vectors. After that
you just do

SimplePrintFunctor(myvector);
[..]

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 28 '06 #3
"PolkaHead" <sc***********@gmail.comwrote:
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.
If you used an Array2D class instead of nested vectors, it would be
quite simple.

template < typename T, typename rep_type = typename std::deque< T
class Matrix
{
public:
typedef typename rep_type::size_type size_type;
typedef typename rep_type::reference reference;
typedef typename rep_type::const_reference const_reference;
typedef typename rep_type::iterator iterator;
typedef typename rep_type::const_iterator const_iterator;

Matrix(): _width( 0 ), _height( 0 ) { }
Matrix( size_type w, size_type h ):
_width( w ), _height( h ), _rep( w * h ) { }

size_type width() const { return _width; }
size_type height() const { return _height; }

reference at( size_type x, size_type y ) {
if ( x >= _width || y >= _height )
throw std::out_of_range( "Matrix::at(size_type, size_type)" );
return _rep[ x * _width + y ];
}

const_reference at( size_type x, size_type y ) const {
if ( x >= _width || y >= _height )
throw std::out_of_range( "Matrix::at(size_type, size_type)" );
return _rep[ x * _width + y ];
}

iterator begin() { return _rep.begin(); }
const_iterator begin() const { return _rep.begin(); }
iterator end() { return _rep.end(); }
const_iterator end() const { return _rep.end(); }

void swap( Matrix& m ) {
std::swap( _width, m._width );
std::swap( _height, m._height );
_rep.swap( m._rep );
}

private:
typename rep_type::size_type _width, _height;
rep_type _rep;
};

Matrix<ElementmyMatrix( 2, 3 );
// load
for_each( myMatrix.begin(), myMatrix.end(),
std::mem_fun( &Element::printName ) );

--
To send me email, put "sheltie" in the subject.
Nov 29 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Christof Krueger | last post by:
Hello, I'm quite new to C++ so maybe there's something I miss. I write a simple board game. It has a board class. This class has a method that returns the count of pieces a player has on the...
2
by: Eric Lilja | last post by:
Hello, I have a std::vector storing pointers to objects that are dynamically allocated. When I am done with the vector I want to delete all pointers. Can I use std::for_each() or something to do...
12
by: sashan | last post by:
Sometimes I write code using std::for_each. Sometimes I use it on several container classes that are the same size. for_each(v.begin(), v.end(), f1()); for_each(u.begin(), u.end(), f2()); ...
7
by: nabeel.girgis | last post by:
I am passing a vector by reference into a function and I am trying to use a pointer in that function. I get an error saying : '=' : cannot convert from 'std::vector<_Ty> *' to 'int *' when I...
27
by: Fraser Ross | last post by:
Is it wrong to describe for_each as a modifying algorithm? It is described as one here: http://www.josuttis.com/libbook/algolist.pdf. transform appears to be the algorithm to use for modifying...
1
nabh4u
by: nabh4u | last post by:
Hi, I have a problem referencing to Vectors using pointers i.e. I am not able to use "call by reference" on vector variables. I have a "read()" function in "x.cpp" and "main()" in "y.cpp". I...
3
by: Yan | last post by:
Hi, I don't seem to be able to use for_each if it should replace a 'for' loop in a method (constructor in my case) and inside that 'for' loop a class member variable is being accessed. The...
2
by: Sarath | last post by:
I've two vectors vectorA and vectorB. I've copy some elements from vectorA to B on satisfying some conditions. I'd like to avoid for loop and comparison routines. It would appreciate if there are...
4
by: Yan | last post by:
I have a vector of elements which I iterate through and call a method on each of the elements. I want to do it using std::for_each algorithm, but having a problem implementing it since the method...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.