c++ - 遍历不同类型集合的通用代码

标签 c++ stl

是否有一个优雅的解决方案来使用通用代码遍历 hash_map/unordered_maplist/vector收藏?

一个例子:

template<typename collection>
class multicast
{
public:
    typedef collection collection_type;

private:
    collection_type& m_channels;

public:
    multicast(collection_type& channels) : m_channels(channels) { }

    void operator ()(const buffer::ptr& head, const buffer::ptr& cnt)
    {
        for each(collection_type::value_type& ch in m_channels)
            ch->send(head, cnt); /* this is where the magic should happen? */
    }
}

collection_typeunordered_map 时,这段代码显然无法编译,因为 collection_type::value_type 是一个 pair 所以访问实际值的代码应该不同:ch.second->send(head, cnt) 而不是 ch->send(head, cnt)。那么,什么是在不需要关键部分时删除关键部分的最优雅方法呢?

最佳答案

是的:

for (auto & x : collection) { do_stuff_with(x); }

或者:

for (auto it = std::begin(collection), end = std::end(collection); it != end; ++it)
{
    do_stuff_with(*it);
}

如果既不是基于范围的for也不auto可用,您可以编写一个带有容器的模板 C并使用 C::value_typeC::iterator ;或者你可以制作一个模板,它接受一对类型为 Iter迭代器并使用 std::iterator_traits<Iter>::value_type为元素值类型。

第三,你可以使用for_each和一个 lambda:

std::for_each(colllection.begin(), collection.end(),
              [](collection::value_type & x) { do_stuff_with(x); });


为了适应单元素和双元素容器,您可以构建一个小包装器:

template <typename T> struct get_value_impl
{
    typedef T value_type;
    static value_type & get(T & t) { return t; }
};
template <typename K, typename V> struct get_value_impl<std::pair<K, V>>
{
    typedef V value_type;
    static value_type & get(std::pair<K,V> & p) { return p.second; }
};
template <typename T>
typename get_value_impl<T>::value_type & get_value(T & t)
{
    return get_value_impl<T>::get(t);
}

现在您可以使用 get_value(x)get_value(*it)只获取值。

关于c++ - 遍历不同类型集合的通用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883971/

相关文章:

c++ - 在类声明或构造函数初始化列表中初始化简单成员

c++ - 是否有不需要 C++ 运行时的 SQLite C# 库?

c++ - 在软件中实现线程本地存储

c++ - 从 std::string 隐式转换为 eaSTL::string

c++ - 如何修复 "error: ‘_1’ 未在此范围内声明”?

c++ - 在比较用 C++ 编写的两种不同算法时,您使用的优化级别 (g++) 是多少?

c++ - 如何传递用户数据来比较 std::sort 的功能?

c++ - 转换宽字符串以 boost 日期

c++ - STL函数来测试一个值是否在某个范围内?

c++ - hash_set 中不能包含用户定义的类