473,657 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

}

Nov 28 '06 #1
3 2864
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(?, ?, SimplerPrintFun ctor() );,
If you templatize your 'SimplePrintFun ctor', something like

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

template<class T>
void SimplePrintFunc tor(std::vector <Tconst& vt)
{
for_each(vt.beg in(), vt.end(), SimplePrintFunc tor);
}

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

SimplePrintFunc tor(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 SimplePrintFunc tor...
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(?, ?, SimplerPrintFun ctor() );,

If you templatize your 'SimplePrintFun ctor', something like

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

template<class T>
void SimplePrintFunc tor(std::vector <Tconst& vt)
{
for_each(vt.beg in(), vt.end(), SimplePrintFunc tor);
}

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

SimplePrintFunc tor(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::refer ence reference;
typedef typename rep_type::const _reference const_reference ;
typedef typename rep_type::itera tor 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_ran ge( "Matrix::at(siz e_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_ran ge( "Matrix::at(siz e_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<Elementm yMatrix( 2, 3 );
// load
for_each( myMatrix.begin( ), myMatrix.end(),
std::mem_fun( &Element::print Name ) );

--
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
1924
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 board. Since this function does not change anything in the class I declared it as const. To count all pieces of a given color the functions iterates through a "map" of CNode-pointers. "CNode" is another class that is irrelevant to the problem.
2
1759
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 that in one line? I am so tired of seeing the following in my code: for(vector<some_type>::size_type i = 0; i < myvec.size(); ++i) do_something_with_each_element; / Eric
12
2606
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()); This seems inefficient so I rewrite it as: int n = v.size(); for (int i = 0; i < n; ++i)
7
1963
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 try to initialize the pointer to point to the vector. This is my first time using pass by reference into a function while trying to declare a pointer in the same function. My code is given below.
27
2222
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 elements in a range. Fraser. Posted Via Usenet.com Premium Usenet Newsgroup Services
1
2452
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 have 3 vector variables in Main(). I want the read function to read the values into the vector using the address I send of the vectors.. Sample code: //x.cpp void read(vector <int> a,vector <int> b,vector < vector <int> > c)
3
1571
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 presence of this member variable prevents me from using a static or global method to be passed as a third parameter to for_each, and mem_fun doesn't seem to work for me either as I am not going to execute a method of an iterator but pass an iterator...
2
2098
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 any stl routines/classes can help on this matter. I tried using for_each but still passing elements still a problem. e.g stuct Test {
4
2457
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 that I call on each element takes an argument and I don't know how to pass this argument through. Here is the code using an old fashioned loop: ....... std::vector<unsigned char bytes; std::vector<Telements; ....
0
8411
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8323
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8739
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7351
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2740
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1732
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.