【发布时间】:2017-06-16 11:52:41
【问题描述】:
我想使用BOOST_FOREACH 来迭代boost::ptr_map,然后遇到this neat-looking solution。与给出的其他解决方案相比,我更喜欢使用它以获得更好的可读性。我写了以下代码:
boost::ptr_map<int, std::string> int2strMap;
int x = 1;
int2strMap.insert(x, new std::string("one"));
int one;
std::string* two;
BOOST_FOREACH(::boost::tie(one, two), int2strMap)
{
std::cout << one << two << std::endl;
}
但是,这无法编译,并给我以下错误(完整的错误消息还有几行,如果我应该粘贴它们,请告诉我。):
error: no match for 'operator=' (operand types are 'boost::tuples::detail::tie_mapper<int, std::basic_string<char>*, void, void, void, void, void, void, void, void>::type {aka boost::tuples::tuple<int&, std::basic_string<char>*&, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type>}' and 'boost::iterators::iterator_reference<boost::ptr_map_iterator<std::_Rb_tree_iterator<std::pair<const int, void*> >, int, std::basic_string<char>* const> >::type {aka boost::ptr_container_detail::ref_pair<int, std::basic_string<char>* const>}')
BOOST_FOREACH(::boost::tie(one, two), int2strMap)
建议的解决方案似乎适用于少数人,但我无法弄清楚为什么它不适合我。我在这里做错了什么?
(注意:我正在做一个史前项目,所以坚持使用 C++03。g++ 版本:4.8.4)
【问题讨论】:
-
如果不检查胆量就不能确定,但这可能与您不能使用
std::tuple执行此操作的原因相同。它只能使用编译时构造进行迭代。 -
我怀疑这个看起来整洁的解决方案是否可行,因为它希望迭代器给我们一个
std::pair,但我们只得到kinda looks like it的东西。 (自发布该答案以来,代码似乎没有更改) -
但是,您可以实现自己的简单
tie等价物 -- like this。 -
@Dan 这当然是一种可能性,但我希望 7 个人不会在不检查它是否正确的情况下投票。嗯……
-
@MaskedMan 在对提升报告进行了更多挖掘之后,我确信它永远不会起作用。至于你说的话,这很可悲,但是在看到大量对完全垃圾的支持以及无数各种懒惰的例子后,我倾向于对选票持保留态度——尤其是当答案没有任何参考资料时,工作(最好是现场)样本等