【问题标题】:C++ map iterator over valuesC ++映射迭代器
【发布时间】:2021-04-15 17:02:07
【问题描述】:

我有这个代码:

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&lt;packed_time, route_departure_o&gt;;,我想以迭代器仅引用值而不是对的方式遍历此映射。

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

【问题讨论】:

    标签: c++ hashmap iterator


    【解决方案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 的一个普通的、非常量的别名,所以您使用它的方式相同。

    【讨论】:

    • 现在我有编译器错误,C4430 缺少类型说明符,对于 reference operator*() { return i-&gt;second; }pointer operator-&gt;() { return &amp;i-&gt;second; }
    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2023-03-31
    • 2010-11-29
    相关资源
    最近更新 更多