Renaming first and second of a map iterator

后端 未结 8 1727
北恋
北恋 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 03:04

    I liked KeithB's solution with free functions. However, a more reusable solution might be nice.

    What about function objects that access first or second, as you can name the instances anything you like:

    #include 
    #include 
    #include 
    
    struct GetFirst
    {
        template 
        First& operator()(std::pair& p)
        {
            return p.first;
        }
    
        template 
        const First& operator()(const std::pair& p)
        {
            return p.first;
        }
    };
    
    struct GetSecond
    {
        template 
        Second& operator()(std::pair& p)
        {
            return p.second;
        }
    
        template 
        const Second& operator()(const std::pair& p)
        {
            return p.second;
        }
    };
    
    int main()
    {
        typedef std::map Map;
    
        Map persons;
        persons["John"] = 20;
        persons["Mary"] = 24;
    
        //create named accessors
        GetFirst name;
        GetSecond age;
    
        for (Map::iterator it = persons.begin(); it != persons.end(); ++it) {
            std::cout << name(*it) << " is aging.\n";
            ++age(*it);
        }
    
        for (Map::const_iterator it = persons.begin(); it != persons.end(); ++it) {
            std::cout << "Name: " << name(*it) << ", age: " << age(*it) << '\n';
        }
    }
    

    This is the best I could do. I also tried to make those functors accept the iterator directly, but one way or another this means that the signature will contain dependent names which apparently makes template type deduction impossible (I couldn't find a way to overload GetSecond for iterator/const_iterator even with deferred return type of C++0x).

提交回复
热议问题