是否有一个优雅的解决方案来使用通用代码遍历 hash_map
/unordered_map
和 list
/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_type
是 unordered_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_type
和 C::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/