如何将 BOOST_FOREACH 与 boost::ptr_map 一起使用?

2023-07-19C/C++开发问题
4

本文介绍了如何将 BOOST_FOREACH 与 boost::ptr_map 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何通过 boost::ptr_map 有效地使用 BOOST_FOREACH(字符数/可读性)?

How can I use BOOST_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr_map?

Kristo 在他的回答中证明这是可能的将 BOOST_FOREACH 与 ptr_map 一起使用,但与使用迭代器迭代 ptr_map 相比,它并没有真正为我节省任何输入(或使我的代码真正更具可读性):

Kristo demonstrated in his answer that it is possible to use BOOST_FOREACH with a ptr_map, but it does not really save me any typing (or makes my code really more readable) than iterating over the ptr_map with an iterator:

typedef boost::ptr_container_detail::ref_pair<int, int* const> IntPair;
BOOST_FOREACH(IntPair p, mymap) {
    int i = p.first;
}

// vs.

boost::ptr_map<int, T>::iterator it;
for (it = mymap.begin(); it != mymap.end(); ++it) {
    // doSomething()
}

以下代码符合我的愿望.它遵循有关如何将 BOOST_FOREACH 与 std::map 一起使用的标准方法.不幸的是,这不能编译:

The following code is somewhere along the lines what I wish for. It follows the standard way on how to use BOOST_FOREACH with a std::map. Unfortunately this does not compile:

boost::ptr_map<int, T> mymap;
// insert something into mymap
// ...

typedef pair<int, T> IntTpair;
BOOST_FOREACH (IntTpair &p, mymap) {
    int i = p.first;
}

推荐答案

作为 STL 风格的容器,指针容器有一个 value_type 类型定义,你可以使用:

As STL style containers, the pointer containers have a value_type typedef that you can use:

#include <boost/ptr_container/ptr_map.hpp>
#include <boost/foreach.hpp>

int main()
{
    typedef boost::ptr_map<int, int> int_map;
    int_map mymap;

    BOOST_FOREACH(int_map::value_type p, mymap)
    {
    }
}

我发现为容器使用 typedef 会使代码更容易编写.

I find that using a typedef for the container makes the code a lot easier to write.

另外,你应该尽量避免在 boost 中使用 detail 命名空间的内容,这是一个包含实现细节的 boost 约定.

Also, you should try to avoid using the contents of detail namespaces in boost, it's a boost convention that they contain implementation details.

这篇关于如何将 BOOST_FOREACH 与 boost::ptr_map 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6