如何将 BOOST_FOREACH 与两个 std::map 一起使用?
我的代码基本上如下所示:
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...
}
有没有办法连接映射以消除第二个循环中的重复代码? 或者一种扩展 BOOST_FOREACH 一次性迭代两个不同映射的方法? 显然我不想增加程序的时间复杂度(否则我可以创建一个新地图并插入其中map1和map2)。 我有一种感觉,我在这里缺少一些基本的东西。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以定义一个函数:
尽管在这种情况下使用 std::for_each 可能更简单:
You could define a function:
Although in that case it might be even simpler to use
std::for_each
:这里的想法是编写一种特殊类型的迭代器来虚拟地合并两个容器,就 BOOST_FOREACH 而言。 请注意,我不会从两个现有容器中创建新容器。 我只是从第一个容器的 end() 迭代器跳转到第二个容器的 begin() 迭代器。
我没有尝试编写实际的 merged_iterator 类,但虽然写起来可能有点长,但技术上并不困难。 事实上,我很惊讶没有使用谷歌找到类似的东西。 不过我没找多久!
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 !
除了我推荐的1800的解决方案之外,还有各种hacky解决方案:
注意:当我看到同事这样写代码时,有时我会忍不住想掐死他们。 使用风险自负。
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.
在我的头顶上,我会尝试
Of the top of my head, I'd try
此处进行了解释。
你可以这样做:
It's explained here.
You can do this: