将 BOOST_FOREACH 与 std::map 一起使用
我想使用 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
当然,这不会改变任何东西,因为我不是通过引用进行迭代。 因此,我替换了这一行(按照 Boost 文档中的示例):
BOOST_FOREACH( IdSizePair_t &i, mmap )
并且我收到编译器错误:
error C2440: 'initializing' :
cannot convert from 'std::pair<_Ty1,_Ty2>' to 'IdSizePair_t &'
with
[
_Ty1=const int,
_Ty2=int
]
有什么建议吗?
I'd like to iterate over a std::map using BOOST_FOREACH and edit the values. I can't quite get it.
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_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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题出在该对的第一个成员上,它应该是 const。 尝试这个:
The problem is with the first member of the pair, which should be const. Try this:
这是一个旧线程,但有一个更方便的解决方案。
boost 具有“范围适配器”的概念,可以对迭代器范围执行转换。 对于这个具体用例(迭代映射键或值)有特定的范围适配器:boost::adaptors::map_values 和 boost::adaptors::map_keys。
因此,您可以像这样迭代映射值:
更多信息此处< /a>.
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
andboost::adaptors::map_keys
.So you could iterate over map values like this:
More information here.
另一种选择是使用 BOOST_FOREACH_PAIR,请在此处查看我的答案:
BOOST_FOREACH & 没有 typedef 的模板
Another option is to use BOOST_FOREACH_PAIR, see my answer here:
BOOST_FOREACH & templates without typedef
从 C++11 开始考虑使用 auto 关键字:
As of C++11 consider using auto keyword: