473,394 Members | 1,738 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,394 software developers and data experts.

non-const for_each usage

Hi NG,

I have a question on std::for_each. I try to use this in combination
with std::bind2nd to call a method of all functions in a container
(std::set or std::map) and pass that method the second argument of
std::bind2nd.
But for some reason the compiler wants met ot have all const objects,
which obviously doesn't work when the method is non-const.
example:

/** test.cpp **/
#include <set>
#include <algorithm>

class myInt
{
int i_;
public:
myInt(int i): i_(i) {}
int val() const { return i_; }
void setVal(int i) { i_ = i; }
bool operator<(const myInt & rhs) const { return i_ < rhs.i_; }
};

struct intAdder : public std::binary_function<myInt,int,void>
{
void operator()(myInt & ref, int x) const
{
ref.setVal(ref.val() + x);
}
};

int main()
{
std::set<myInt> s;

s.insert( myInt( 3 ) );
s.insert( myInt( 5 ) );

std::for_each(s.begin(), s.end(), std::bind2nd(intAdder(), 2));

return 0;
}

The interesting thing is that this code does compile with
cl /Zi /GX /GR test.cpp (win32 13.10.3077)

but doesn't compile with
g++ -W -Wall test.cpp (gcc 3.2.3)

Mark
Sep 20 '05 #1
1 1850
"Capstar" wrote:
Hi NG,

I have a question on std::for_each. I try to use this in combination
with std::bind2nd to call a method of all functions in a container
(std::set or std::map) and pass that method the second argument of
std::bind2nd.
But for some reason the compiler wants met ot have all const objects,
which obviously doesn't work when the method is non-const.
example:

/** test.cpp **/
#include <set>
#include <algorithm>

class myInt
{
int i_;
public:
myInt(int i): i_(i) {}
int val() const { return i_; }
void setVal(int i) { i_ = i; }
bool operator<(const myInt & rhs) const { return i_ < rhs.i_; }
};

struct intAdder : public std::binary_function<myInt,int,void>
{
void operator()(myInt & ref, int x) const
{
ref.setVal(ref.val() + x);
}
};

int main()
{
std::set<myInt> s;

s.insert( myInt( 3 ) );
s.insert( myInt( 5 ) );

std::for_each(s.begin(), s.end(), std::bind2nd(intAdder(), 2));

return 0;
}

The interesting thing is that this code does compile with
cl /Zi /GX /GR test.cpp (win32 13.10.3077)

but doesn't compile with
g++ -W -Wall test.cpp (gcc 3.2.3)

Mark


Upon looking at page 519 of Stroustrup's "C++ Programming Language"
I see that the application operator of class "binder2nd" takes a
constant ref argument. Hence the embedded "binary operation"
cannot change its left argument.

Stroustrup implies that bind2nd and binder2nd are intended for
manufacturing predicates which return booleans and don't alter
their arguments.

Another problem is, I don't think std::set has an asignment
operator for elements. You're supposed to use insert, erase,
etc., instead of "=". Which is why for_each sees the elements
of your set as being "const".

For one thing, std::set has a rule that no two values can
be equal. A "=" operator would allow the user to contravene
that rule, which is why there's "insert" and "erase", so that
std::set can enforce it's "no duplicates" rule.

To illustrate, if you changed your set to a list, and also
changed the bind2nd to a functor, the altered program compiles
and runs fine:

#include <set>
#include <algorithm>
#include <list>

class myInt
{
int i_;
public:
myInt(int i): i_(i) {}
int val() const { return i_; }
void setVal(int i) { i_ = i; }
bool operator<(const myInt & rhs) const { return i_ < rhs.i_; }
};

struct intAdder
{
int Right;
intAdder(int R) : Right(R) {}
void operator()(myInt & Left) {Left.setVal(Left.val() + Right);}
};

int main()
{
std::list<myInt> s;

s.push_back( myInt( 3 ) );
s.push_back( myInt( 5 ) );

std::for_each(s.begin(), s.end(), intAdder(2));

return 0;
}
So your problems really had nothing to do with for_each, but
rather with your usage of bind2nd and std::set.

If you really need a std::set, I don't think you can use
for_each (or anthing else, for that matter) to alter the elements.
I believe the elements are unalterable. You can replace them
by "erase(5); insert(7);". But you can't do THIS:
#include <set>
int main(void)
{
std::set<int> s;
s.insert( 3 );
s.insert( 5 );
(*(s.begin())) = 9; // ILLEGAL
return 0;
}

Compiler error reads: "Error: asignment to read-only location!"

Sets just don't work that way.

--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
Sep 20 '05 #2

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

Similar topics

12
by: lothar | last post by:
re: 4.2.1 Regular Expression Syntax http://docs.python.org/lib/re-syntax.html *?, +?, ?? Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few...
3
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in...
25
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
8
by: Bern McCarty | last post by:
Is it at all possible to leverage mixed-mode assemblies from AppDomains other than the default AppDomain? Is there any means at all of doing this? Mixed-mode is incredibly convenient, but if I...
14
by: Patrick Kowalzick | last post by:
Dear all, I have an existing piece of code with a struct with some PODs. struct A { int x; int y; };
11
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the...
2
by: Ian825 | last post by:
I need help writing a function for a program that is based upon the various operations of a matrix and I keep getting a "non-aggregate type" error. My guess is that I need to dereference my...
0
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome...
399
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or...
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: 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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.