是否可以将 boost::foreach 与 std::map 一起使用?

2021-12-24 00:00:00 foreach c++ boost

我发现 boost::foreach 非常有用因为它为我节省了很多写作时间.例如,假设我想打印列表中的所有元素:

I find boost::foreach very useful as it saves me a lot of writing. For example, let's say I want to print all the elements in a list:

std::list<int> numbers = { 1, 2, 3, 4 };
for (std::list<int>::iterator i = numbers.begin(); i != numbers.end(); ++i)
   cout << *i << " ";

boost::foreach 使上面的代码更加简单:

boost::foreach makes the code above much simplier:

std::list<int> numbers = { 1, 2, 3, 4 };
BOOST_FOREACH (int i, numbers)
   cout << i << " ";

好多了!但是我从来没有想出一种方法(如果可能的话)将它用于 std::map s.该文档仅包含具有 vectorstring 等类型的示例.

Much better! However I never figured out a way (if it's at all possible) to use it for std::maps. The documentation only has examples with types such as vector or string.

推荐答案

您需要使用:

typedef std::map<int, int> map_type;
map_type map = /* ... */;

BOOST_FOREACH(const map_type::value_type& myPair, map)
{
    // ...
}

原因是宏需要两个参数.当您尝试内联对定义时,您引入了第二个逗号,使宏改为三个参数.预处理器不尊重任何 C++ 结构,它只知道文本.

The reason being that the macro expects two parameters. When you try to inline the pair definition, you introduce a second comma, making the macro three parameters instead. The preprocessor doesn't respect any C++ constructs, it only knows text.

所以当你说 BOOST_FOREACH(pair, map) 时,预处理器会看到宏的这三个参数:

So when you say BOOST_FOREACH(pair<int, int>, map), the preprocessor sees these three arguments for the macro:

1.pair
2. int>
3. 地图

这是错误的.这是在 for-each 中提到文档.

Which is wrong. This is mentioned in the for-each documentation.

相关文章