有什么方法可以编写一个通用循环来迭代 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/