问题描述
我觉得非常有用,因为它为我节省了不少著述。例如,假设我想打印列表中的所有元素:
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使得code以上多simplier:
boost::foreach makes the code above much simplier:
std::list<int> numbers = { 1, 2, 3, 4 };
BOOST_FOREACH (int i, numbers)
cout << i << " ";
好多了!不过,我从来没有想出一个办法(如果它是在所有可能的),用它来的std ::地图
秒。文档只与类型的例子,如矢量
或字符串
。
Much better! However I never figured out a way (if it's at all possible) to use it for std::map
s. 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)
{
// ...
}
原因是,宏需要两个参数。当您尝试内联对定义,您引入第二个逗号,使得宏观三个参数来代替。在preprocessor不尊重任何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(对&LT; INT,INT&gt;中图)
中,preprocessor看到这三个参数的宏:
So when you say BOOST_FOREACH(pair<int, int>, map)
, the preprocessor sees these three arguments for the macro:
1 对&LT; INT
结果
2. INT&GT;
结果
3. 地图
这是错误的。这是换每个文档中提到 。
Which is wrong. This is mentioned in the for-each documentation.
这篇关于是否有可能使用boost ::使用的foreach的std ::地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!