473,769 Members | 2,106 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_fun ction<myInt,int ,void>
{
void operator()(myIn t & 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(in tAdder(), 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 1878
"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_fun ction<myInt,int ,void>
{
void operator()(myIn t & 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(in tAdder(), 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()(myIn t & Left) {Left.setVal(Le ft.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
4429
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 characters as possible will be matched. the regular expression module fails to perform non-greedy matches as described in the documentation: more than "as few characters as possible"
3
12263
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 nonblocking mode in c++? I did something ugly like --- c/c++ mixture --- mkfifo( "testpipe", 777);
25
7644
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
4526
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
8
3514
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 cannot load/unload/reload extensions into my large and slow-to-load application during development without restarting the process then the disadvantages may outweigh the advantages. I've got a mixed-mode program in which I create a new AppDomain...
14
8466
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
3453
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 vtable pointer is made use of.. eg. class one {
2
6118
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 pointers, but I'm not sure. Please help. The code: void equate(matrix *A, matrix *B) { int i, j; assert(A.row_dim == B.col_dim && A.col_dim == B.col_dim); for(i=0; i < A.row_dim; i++) for(j=0; j < A.col_dim; j++)
0
2345
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 jobs. When a non-secure page references a secure page with relative URL, the web server generates error until absolute URL with https prefix is used. On the other hand when a secure page references a non-secure page, the non-secure page will be...
399
12938
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 to python-3000@python.org In summary, this PEP proposes to allow non-ASCII letters as identifiers in Python. If the PEP is accepted, the following identifiers would also become valid as class, function, or variable names: Löffelstiel,...
0
9589
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
9423
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
10049
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...
0
9865
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
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...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
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
3
2815
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.