Keys / Values Functionality to Iterators in C++

后端 未结 1 1149
你的背包
你的背包 2021-01-02 15:23

I know this questions has come up in various guises before, but this is slightly different.

I have a class which contains a std::map. Although I wish to use the map

1条回答
  •  [愿得一人]
    2021-01-02 15:53

    Have a look at Boost's transform_iterator which provides exactly this kind of functionality:

    template 
    struct get_value {
        const V& operator ()(std::pair const& p) { return p.second; }
    };
    
    class your_class {
        typedef map TMap;
        TMap mymap;
    
    public:
        typedef get_value F;
        typedef
            boost::transform_iterator
            value_iterator;
    
        value_iterator begin() { return make_transform_iterator(mymap.begin(), F()); }
    
        value_iterator end() { return make_transform_iterator(mymap.end(), F()); }
    
        // TODO Same for const versions.
        // Rest of the interface …
    };
    

    Now you can iterate over the values, e.g. like this:

    your_class c;
    // Fill c with some values …
    copy(c.begin(), c.end(), ostream_iterator(cout, " "));
    

    0 讨论(0)
提交回复
热议问题