Renaming first and second of a map iterator

后端 未结 8 1725
北恋
北恋 2020-12-14 02:41

Is there any way to rename the first and second accessor functions of a map iterator. I understand they have these names because of the underlying pair which represents the

8条回答
  •  粉色の甜心
    2020-12-14 02:53

    I wouldn't recommend really using this, but it does seem to work, at least to the minimum degree of the test program doing what I wanted/expected:

    #include 
    #include 
    #include 
    
    template 
    struct my_pair : public std::pair {
        T const &vertex;
        my_pair(std::pair const &x) : std::pair(x), vertex(x.first) { }
    };
    
    template 
    struct my_map : public std::map { 
        my_pair find(T const &t) { return my_pair(*std::map::find(t)); }
    };
    
    class Vertex { 
        int x;
    public:
        Vertex(int v) : x(v) {}
        bool operator<(Vertex const &other) const { return x < other.x; }
        friend std::ostream &operator<<(std::ostream &os, Vertex const &v) { return os << v.x; }
    };
    
    int main() { 
        my_map m;
    
        m[1] = "This is it";
    
        my_pair mp = m.find(1);
        std::cout << mp.vertex << ": " << mp.second;
        return 0;
    }
    

提交回复
热议问题