Use of for_each on map elements

前端 未结 11 728
北荒
北荒 2021-01-30 10:29

I have a map where I\'d like to perform a call on every data type object member function. I yet know how to do this on any sequence but, is it possible to do it on an associativ

11条回答
  •  不思量自难忘°
    2021-01-30 11:09

    It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:

    #include 
    #include 
    #include    // GNU-specific extension for functor classes missing from standard STL
    
    using namespace __gnu_cxx;  // for compose1 and select2nd
    
    class MyClass
    {
    public:
        void Method() const;
    };
    
    std::map Map;
    
    int main(void)
    {
        std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd::value_type>()));
    }
    

    Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.

提交回复
热议问题