如何使用BOOST_FOREACH与两个std :: maps? [英] How to use BOOST_FOREACH with two std::maps?

查看:156
本文介绍了如何使用BOOST_FOREACH与两个std :: maps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码看起来基本上是这样:

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...
}


b $ b

有没有办法连接映射以消除第二个循环中的重复代码?还是一种方法来扩展BOOST_FOREACH来一次迭代两个不同的地图?显然,我不想增加程序的时间复杂度(否则我可以创建一个新的地图,并插入到它map1和map2)。

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.

推荐答案

您可以定义一个函数:

typedef std::map<int, int> IntMap;

void doStuffWithInt(IntMap::value_type &i)
{
  // steps 1 to 5
}

BOOST_FOREACH(IntMap::value_type &i, map1)
  doStuffWithInt(i);
BOOST_FOREACH(IntMap::value_type &i, map2)
  doStuffWithInt(i);

虽然在这种情况下,使用 std :: for_each

Although in that case it might be even simpler to use std::for_each:

for_each(map1.begin(), map1.end(), doStuffWithInt);
for_each(map2.begin(), map2.end(), doStuffWithInt);

这篇关于如何使用BOOST_FOREACH与两个std :: maps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆