I have code that looks essentially like this:
std::map<int, int> map1, map2;
BOOST_FOREACH(int i, map1)
{
// do steps 1-5 here...
}
BOOST_FOREACH(int i, map2)
{
// do steps 1-5 (identical to above) here...
}
Is there any way to concatenate the maps to eliminate the duplicate code in the second loop? Or a way to extend BOOST_FOREACH to iterate over two different maps in one go? Obviously I don't want to increase the time complexity of the program (otherwise I could just create a new map and insert into it map1 and map2). I have a feeling I am missing something rudimentary here.
It's explained here.
You can do this:
Of the top of my head, I'd try
The idea here is to write a special type of iterators to virtually merge two containers, as far as BOOST_FOREACH is concerned. Note that i am not creating a new container out of the two existing ones. I am simply jumping from the first container's end() to the second container's begin() iterator. I did not try and write the actual merged_iterator class, but although it might a bit long to write, it's not technically difficult. I am actually surprised not to have found something like that using google. I did not look for long, though !
You could define a function:
Although in that case it might be even simpler to use
std::for_each
:In addition to 1800's solution, which I would recommend, there's also various hacky solutions:
Note: when I see colleagues write code like this, sometimes I am overcome by an irresistible urge to go strangle them. Use at your own risk.
The easiest way is like this:
And don't worry those commas won't confuse the preprocessor because of the parenthesis.