473,568 Members | 2,762 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about using for_each

Yan
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 as a parameter. I am not sure that explanation makes
a lot of sense, so below is a sample code. I would like to be able to
replace the 'for' loop inside C class constructor with a for_each.
Please don't pay attention to what is actually happening with these
two vectors of ints, it's just for illustration purposes. Thanks.

-----------------------------------------------------------

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

typedef vector<intvecto rInts;
typedef vector<int>::it erator vectorIntsIter;

class C {
public:

C(pair<vectorIn tsIter, vectorIntsItera Pair) {
for (vectorIntsIter iter = aPair.first; iter != aPair.second; +
+iter) {
// do something that involves member variable
// which seems to prevent using a static method
// such as for example this:
ints.push_back( *iter + 10);
}
}

void printAllElement s() {
// here a static method 'print' is successfully used
for_each(ints.b egin(), ints.end(), print);
}

private:
static void print(int number) {
cout << number << endl;
}
private:
vectorInts ints;
};

int main() {
vectorInts ints;

ints.push_back( 0);
ints.push_back( 1);
ints.push_back( 2);
ints.push_back( 3);

pair<vectorInts Iter, vectorIntsItera Pair(ints.begin (),
ints.end());
C c(aPair);
c.printAllEleme nts();

return 0;
}

Jul 11 '07 #1
3 1563
On Jul 11, 2:24 pm, Yan <yvinogra...@gm ail.comwrote:
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 as a parameter. I am not sure that explanation makes
a lot of sense, so below is a sample code. I would like to be able to
replace the 'for' loop inside C class constructor with a for_each.
Please don't pay attention to what is actually happening with these
two vectors of ints, it's just for illustration purposes. Thanks.
[snipped original code using for()]

How about something like this:

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

class push_back_doubl e
{
public:
push_back_doubl e( vector<int& ints ) : p_ints( &ints ) {}

void operator() ( const int & i )
{
p_ints->push_back( i*2 );
}

private:
vector<int*p_in ts;
};

class Test
{
public:
Test( vector<int>::it erator first, vector<int>::it erator last )
{
for_each( first, last, push_back_doubl e(ints));
}

void Dump()
{
copy( ints.begin(), ints.end(),
ostream_iterato r<int>(cout,"\n "));
}

private:
vector<intints;
};

int main()
{
vector<inttest;
test.push_back( 1 );
test.push_back( 2 );
test.push_back( 3 );

Test t( test.begin(), test.end() );
t.Dump();
}

Though I'm pretty sure this could be done cleaner with mem_fun...
I'll try that next.

Cbeers,
Andre

Jul 11 '07 #2
On 7 12 , 5 54 , "int2...@gmail. com" <int2...@gmail. comwrote:
On Jul 11, 2:24 pm, Yan <yvinogra...@gm ail.comwrote:
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 as a parameter. I am not sure that explanation makes
a lot of sense, so below is a sample code. I would like to be able to
replace the 'for' loop inside C class constructor with a for_each.
Please don't pay attention to what is actually happening with these
two vectors of ints, it's just for illustration purposes. Thanks.

[snipped original code using for()]

How about something like this:

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

class push_back_doubl e
{
public:
push_back_doubl e( vector<int& ints ) : p_ints( &ints ) {}

void operator() ( const int & i )
{
p_ints->push_back( i*2 );
}

private:
vector<int*p_in ts;

};

class Test
{
public:
Test( vector<int>::it erator first, vector<int>::it erator last )
{
for_each( first, last, push_back_doubl e(ints));
}

void Dump()
{
copy( ints.begin(), ints.end(),
ostream_iterato r<int>(cout,"\n "));
}

private:
vector<intints;

};

int main()
{
vector<inttest;
test.push_back( 1 );
test.push_back( 2 );
test.push_back( 3 );

Test t( test.begin(), test.end() );
t.Dump();

}

Though I'm pretty sure this could be done cleaner with mem_fun...
I'll try that next.

Cbeers,
Andre
the operator() in the functor is always better a const member function

Jul 12 '07 #3

On 7/11/07 2:24 PM, in article
11************* *********@r34g2 00...legr oups.com, "Yan"
<yv*********@gm ail.comwrote:
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 as a parameter. I am not sure that explanation makes
a lot of sense, so below is a sample code. I would like to be able to
replace the 'for' loop inside C class constructor with a for_each.
Please don't pay attention to what is actually happening with these
two vectors of ints, it's just for illustration purposes. Thanks.

-----------------------------------------------------------

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

typedef vector<intvecto rInts;
typedef vector<int>::it erator vectorIntsIter;

class C {
public:

C(pair<vectorIn tsIter, vectorIntsItera Pair) {
for (vectorIntsIter iter = aPair.first; iter != aPair.second; +
+iter) {
// do something that involves member variable
// which seems to prevent using a static method
// such as for example this:
ints.push_back( *iter + 10);
}
}
A std::for_each() is not the best choice for implementing the loop in the
constructor. I would use std::copy() instead:

copy( aPair.first, aPair.second, back_inserter(i nts) );

Greg

Jul 12 '07 #4

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

Similar topics

2
1512
by: flyaflya | last post by:
i use a class static member function to for_each: class t1 { static test(string s); } main() { list<string> slist; ...
5
5049
by: ogerchikov | last post by:
Hi, I am reading a Boost.lambda example http://www.awprofessional.com/articles/article.asp?p=400651&seqNum=4. Here is the example: void demoVector() { vector<int> myvector; myvector.push_back(1);
5
2284
by: marius lazer | last post by:
I have an STL container of functors and I want to execute them using std::for_each. In the code snippet below the line marked "// good" works fine and the one marked "// nothing" compiles fine but does absolutely nothing. Can anyone explain why? I'm using gcc 4.1.1 on Solaris8. Thanks, Marius #include <iostream>
3
2862
by: PolkaHead | last post by:
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...
3
303
by: hn.ft.pris | last post by:
I've got following code test C++'s functor. For the sake of easy-reading, I omit some declearations. #include <algorithm> #include <functional> using namespace std;
13
4398
by: Sarath | last post by:
What's the advantage of using for_each than the normal iteration using for loop? Is there any 'tweak' to use stream objects as 'Function' parameter of for_each loop. Seems copy function can do the same.
3
1761
by: Nan Li | last post by:
Hello, Can any one explain why the following code cannot get compiled ?? Thanks. #include <iostream> #include <string> #include <vector> #include <iterator> #include <algorithm>
4
1856
by: suman.nandan | last post by:
Hi C++ Experts ! I have a little weird requirement. I have a base class, say B and lots of classes D1 .. Dn publicly derived from it. Over the course of development the number of derived classes may increase. I want that before the execution of one of my particular code, I should have a list of pointers to all the derived classes, say...
4
2453
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: ...
0
7693
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...
0
7916
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8117
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...
1
7660
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...
1
5498
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...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2101
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
0
932
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...

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.