C++ 将 BOOST_FOREACH 与 std::map 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/795443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using BOOST_FOREACH with std::map
提问by kmote
I'd like to iterate over a std::map using BOOST_FOREACH and edit the values. I can't quite get it.
我想使用 BOOST_FOREACH 迭代 std::map 并编辑值。我不太明白。
typedef std::pair<int, int> IdSizePair_t;
std::map<int,int> mmap;
mmap[1] = 1;
mmap[2] = 2;
mmap[3] = 3;
BOOST_FOREACH( IdSizePair_t i, mmap )
i.second++;
// mmap should contain {2,3,4} here
Of course this doesn't change anything because I'm not iterating by reference. So I substitute this line instead (as per the example in the Boost docs):
当然,这不会改变任何东西,因为我不是通过引用进行迭代。所以我替换了这一行(根据 Boost 文档中的示例):
BOOST_FOREACH( IdSizePair_t &i, mmap )
and I get the compiler error:
我得到编译器错误:
error C2440: 'initializing' :
cannot convert from 'std::pair<_Ty1,_Ty2>' to 'IdSizePair_t &'
with
[
_Ty1=const int,
_Ty2=int
]
Any suggestions?
有什么建议?
回答by hvintus
The problem is with the first member of the pair, which should be const. Try this:
问题在于该对的第一个成员,它应该是const。尝试这个:
typedef std::map<int, int> map_t;
map_t mmap;
BOOST_FOREACH( map_t::value_type &i, mmap )
i.second++;
回答by Alex Goldberg
This is an old thread, but there is a more convenient solution.
这是一个旧线程,但有一个更方便的解决方案。
boost has the notion of 'range adapters' that perform a transformation on iterator ranges. There are specific range adapters for this exact use case (iterating over map keys or values): boost::adaptors::map_values
and boost::adaptors::map_keys
.
boost 具有“范围适配器”的概念,可以对迭代器范围执行转换。对于这个确切的用例(迭代映射键或值)有特定的范围适配器:boost::adaptors::map_values
和boost::adaptors::map_keys
.
So you could iterate over map values like this:
所以你可以像这样迭代地图值:
BOOST_FOREACH(int& size, mmap | boost::adaptors::map_values)
{
++size;
}
More information here.
更多信息在这里。
回答by dtw
Another option is to use BOOST_FOREACH_PAIR, see my answer here:
另一种选择是使用 BOOST_FOREACH_PAIR,请在此处查看我的答案:
回答by K.B
As of C++11 consider using auto keyword:
从 C++11 开始考虑使用 auto 关键字:
std::map<int,int> mmap;
mmap[1] = 1;
mmap[2] = 2;
mmap[3] = 3;
BOOST_FOREACH(auto& mpair, mmap)
mpair.second++;
//mmap will contain {2,3,4} here