C++ 映射值迭代器

时间:2021-01-10 15:55:55

标签: c++ hashmap iterator

我有这个代码:

template <typename Iter>
class map_iterator : public std::iterator<std::bidirectional_iterator_tag, typename Iter::value_type::second_type> {
public:
    map_iterator() {}
    map_iterator(Iter j) : i(j) {}
    map_iterator& operator++() { ++i; return *this; }
    map_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; }
    map_iterator& operator--() { --i; return *this; }
    map_iterator operator--(int) { auto tmp = *this; --(*this); return tmp; }
    bool operator==(map_iterator j) const { return i == j.i; }
    bool operator!=(map_iterator j) const { return !(*this == j); }
    reference operator*() { return i->second; }
    pointer operator->() { return &i->second; }
protected:
    Iter i;
};

template <typename Iter>
inline map_iterator<Iter> make_map_iterator(Iter j) { return map_iterator<Iter>(j); }

using route_departure_container = std::map<packed_time, route_departure_o>;

template <typename Iter>
using route_departure_const_iterator = map_iterator;

route_departure_const_iterator departure_at(const std::pair<key, const platform_route_o&>& pr, packed_time tm);

我有地图 using route_departure_container = std::map<packed_time, route_departure_o>;,我想以迭代器仅引用值而不是对 的方式遍历此映射。

我遇到的问题在最后一行 route_departure_const_iterator departure_at(const std::pair<key, const platform_route_o&>& pr, packed_time tm); 中,其中 route_departure_const_iterator 用红色下划线表示:缺少别名模板“route_departure_const_iterator”的参数列表。 我试图在此行上方插入 template <typename Iter> 但它没有帮助。我该怎么办?

1 个答案:

答案 0 :(得分:1)

与您编写上述声明的方式相同:

template <typename Iter>
inline map_iterator<Iter> make_map_iterator(Iter j) { return map_iterator<Iter>(j); }

您还需要编写有问题的声明:

template <typename Iter>
route_departure_const_iterator<Iter> departure_at(const std::pair<key, const platform_route_o&>& pr, packed_time tm);

因为您定义 route_departure_const_iterator 的方式只是 map_iterator 的一个普通的非常量别名,所以您使用相同的方式。