Use of for_each on map elements

前端 未结 11 886
北荒
北荒 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条回答
  •  萌比男神i
    2021-01-30 11:12

    Just an example:

    template 
    class insertIntoVec
    {
    public:
        insertIntoVec(std::vector& vec_in):m_vec(vec_in)
        {}
    
        void operator () (const std::pair& rhs)  
        {   
            m_vec.push_back(rhs.second);
        }
    
    private:
        std::vector& m_vec;
    };
    
    int main()
    {
    std::map aMap;
    aMap[1] = "test1";
    aMap[2] = "test2";
    aMap[3] = "test3";
    aMap[4] = "test4";
    
    std::vector aVec;
    
    aVec.reserve(aMap.size());
    std::for_each(aMap.begin(), aMap.end(),
              insertIntoVec(aVec) 
        );
    

    }

提交回复
热议问题