Reputation: 211
What is the Difference between using BOOST's ForEach and my own custom #define macro to iterate through a container??
mine:
#define iterate(i,x) for(typeof(x.begin()) i=x.begin();i!=x.end();++i)
boost:
#include <string>
#include <iostream>
#include <boost/foreach.hpp>
int main()
{
std::string hello( "Hello, world!" );
BOOST_FOREACH( char ch, hello )
{
std::cout << ch;
}
return 0;
}
Please explain which method is better and why?
Upvotes: 2
Views: 957
Reputation: 18210
First big difference, is when you using rvalues, like this:
vector<int> foo();
// foo() is evaluated once
BOOST_FOREACH(int i, foo())
{
}
// this is evaluated twice(once for foo().begin() and another foo().end())
iterate(i, foo())
{
}
This is because BOOST_FOREACH
detects if it is an rvalue and makes a copy(which can be elided by the compiler).
The second difference is BOOST_FOREACH
uses Boost.Range to retrieve the iterators. This allows it to be extended easily. So it will work on arrays and std::pair
.
The third difference, is your iterate
macro automatically deduces the type of the range, which can be very convenient on older compilers that support typeof
but not auto
. However, BOOST_FOREACH
will work on all C++03 compilers.
Upvotes: 2