我想使用 BOOST_FOREACH
来遍历一个 boost::ptr_map
,并发现了 这个看起来很不错的解决方案。我更喜欢使用它来提高可读性,而不是其他给出的解决方案。我编写了以下代码:
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
做到这一点的原因相同。它只能使用编译时构造进行迭代。 - NathanOliverstd::pair
,但我们只得到了一些类似于它的东西(https://github.com/boostorg/ptr_container/blob/develop/include/boost/ptr_container/detail/map_iterator.hpp#L34)。 (而且自那个答案发布以来,代码似乎没有改变) - Dan Mašek