From: John H. on
On Feb 3, 3:07 pm, NL <norv...(a)gmail.com> wrote:
> How do modify the contents of a container in a for each construct?

Does the following example meet your needs?

#include <vector>
#include <algorithm>

struct Foo
{
int a;
static void Double_a(Foo & f)
{
f.a *= 2;
}
};


int main()
{
Foo const foo1 = { 1 };
Foo const foo2 = { 2 };

std::vector<Foo> fooVector;
fooVector.push_back(foo1);
fooVector.push_back(foo2);

std::for_each(fooVector.begin(), fooVector.end(), Foo::Double_a);

return 0;
}
From: Cholo Lennon on
NL wrote:
> Hi,
>
>>>> try
>>>> for each(Foo &f in FooVector)
>>> I tried that, it gives an error:
>>> error C2440: 'static_cast' : cannot convert from 'const Foo' to 'Foo
>>> &'- Hide quoted text -
>> Sorry. I use the boost library and the code would look like
>>
>> BOOST_FOREACH( Foo &f, FooVector )
>>
>
> I guess I'll switch over to the boost macro, since I'm already using
> other boost stuff in the project. I was leaning toward the MS version
> of for,each,in since it looks more elegant, but I guess it's limited
> to "read-only".
> Also the lack of thorough documentation on it leads me to think it may
> be somewhat temporary.
>

You can use a const reference to avoid copies:

struct Foo {
int a;
}

vector<Foo> FooVector;

for each(const Foo& f in FooVector )
{
...
}

AFAIK using const_cast should work in this case:

for each(const Foo& f in FooVector )
{
const_cast<Foo&>(f).a = some_new_value;
}

A general solution could be:

template<typename T>
class noconst_ref_ptr
{
T* m_ptr;

public:
noconst_ref_ptr(const T& ref) : m_ptr(const_cast<T*>(&ref))
{
}

T* operator->()
{
return m_ptr;
}
};

....

for each(noconst_ref_ptr<Foo> f in FooVector )
{
f->a = some_new_value;
}


At your own risk, or use BOOSR_FOREACH, std::for_each or for :-)


Regards


--
Cholo Lennon
Bs.As.
ARG
From: Tim Roberts on
NL <norvinl(a)gmail.com> wrote:
>
>struct Foo {
> int a;
>}
>vector<Foo> FooVector;
>
>for each( Foo f in FooVector )
>{
> f.a = some_new_value;
>}

I was just about to respond that you were posting in the wrong newsgroup,
because C++ doesn't have a "for each/in" statement, when I decided I should
try it just to confirm. To my utter surprise, this compiles and even works
in VC++ 2008 with native code.

Color me surprised.
--
Tim Roberts, timr(a)probo.com
Providenza & Boekelheide, Inc.