I've found myself writing
for(int i=0;i<myvec.size();i++)
myvec[i]->DoWhatever(param);
a lot, and I'd like to compress this into a foreach
statement, but I'm not sure how to get param
in there without going super-verbose. I've also got things like
for(int i=0;i<myvec.size();i++)
if(myvec[i]->IsOK())
myvec[i]->DoWhatever(param);
and I'd like to rewrite that guy too. Any thoughts?
Oh, also, for various reasons, I don't want to use boost.
You can simplify it by using namespaces...
My preferred solution is usually to write a functor to do what I need:
And then the loop:
Depending on how many variations of this you have, this might be a bit too verbose. There are plenty of options for doing it inline though. boost::lambda would let you construct the function you need at the call-site. boost::bind (or the standard library bind functions) would let you bind the parameter param to the function so you don't need to supply it as an argument every time.
boost::lambda is probably the most concise and flexible approach. I usually use the plain functor approach because the syntax is easier to remember. ;)
If you are using GCC you can define something like:
and use it after like this:
I use this on a custom array but it works fine with std::vector too.
Valid decision, but most likely the wrong one. Consider Boost as an extension to the STL. C++ is a library-driven language. If you don't take this into account, your code will be qualitatively inferior.
While
std::for_each
can be used here, the absence of lambda expressions in C++ until C++0x makes this tedious. I advocate using Boost.ForEach! It makes this much easier:well when we have compilers that support C++0x lambda expresions, this becomes straightforward and minimally invasive:
and the second example may look like this: