c++ - 在 STL 映射和列表上迭代的通用循环 (c++)

标签 c++ templates stl

有什么方法可以编写一个通用循环来迭代 STL 映射(关联容器)和列表(非关联容器)的值。

template<typename T>
void foo(T &t)
{
    for (auto iter = t.begin(); iter != t.end(); ++iter)
    {
        printf("%d\n", *iter); // will work for std::list<int> but not for std::map<int, int>
    }

}

谢谢

最佳答案

要使其适用于 std::map - 使用适当的 adapter来自提升:

foo(someMap | boost::adaptors::map_values);

您也可以使用 Eric Niebler 的 ranges-v3

foo(someMap | ranges::values); 

如果你不能使用 boost/ranges - 使用某种特性:

template <typename ValueType>
struct ValueGetter
{ 
    static Value& get(ValueType& value)
    {
        return value;
    }
};
template <typename Key, typename Value>
struct ValueGetter<std::pair<const Key, Value>>
{ 
    using ValueType = std::pair<const Key, Value>; 
    static Value& get(ValueType& value)
    {
        return value.second;
    }
};

template <typename ValueType>     
auto& getValue(ValueType& value)
{
    return ValueGetter<Value>::get(value);
}

template<typename T>
void foo(T &t)
{
    for (auto iter = t.begin(); iter != t.end(); ++iter)
    {
        printf("%d\n", getValue(*iter)); 
    }

}

关于c++ - 在 STL 映射和列表上迭代的通用循环 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231003/

相关文章:

c++ - 围绕 boost::ptree 头痛的模板化类

c++ - 如何为 lambda 创建唯一类型?

c++ - 为什么 array<T, N> 会比 vector<T> 慢?

c++ - 对使用 STL 并行算法的用户有何限制?

c++ - OpenCV 2.4.3 下载

c++ - linux:如何断开远程用户访问?

c++ - 交互式 shell 中的 Qt 启动进程

c++ - 为什么 C++ 对函数原型(prototype)(签名)的前向声明更加严格?

具有动态回调函数类型的 C++ 模板类

arrays - 来自指针的 std::array 或 std::vector