Use of for_each on map elements

前端 未结 11 718
北荒
北荒 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:12

    C++14 brings generic lambdas. Meaning we can use std::for_each very easily:

    std::map<int, int> myMap{{1, 2}, {3, 4}, {5, 6}, {7, 8}};
    
    std::for_each(myMap.begin(), myMap.end(), [](const auto &myMapPair) {
        std::cout << "first " << myMapPair.first << " second "
                  << myMapPair.second << std::endl;
    });
    

    I think std::for_each is sometimes better suited than a simple range based for loop. For example when you only want to loop through a subset of a map.

    0 讨论(0)
  • 2021-01-30 11:12

    Just an example:

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

    }

    0 讨论(0)
  • 2021-01-30 11:13

    You can iterate through a std::map object. Each iterator will point to a std::pair<const T,S> where T and S are the same types you specified on your map.

    Here this would be:

    for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
    {
      it->second.Method();
    }
    

    If you still want to use std::for_each, pass a function that takes a std::pair<const int, MyClass>& as an argument instead.

    Example:

    void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well
    {
      pair.second.Method();
    }
    

    And pass it to std::for_each:

    std::for_each(Map.begin(), Map.end(), CallMyMethod);
    
    0 讨论(0)
  • 2021-01-30 11:13

    How about a plain C++? (example fixed according to the note by @Noah Roberts)

    for(std::map<int, MyClass>::iterator itr = Map.begin(), itr_end = Map.end(); itr != itr_end; ++itr) {
      itr->second.Method();
    }
    
    0 讨论(0)
  • 2021-01-30 11:19

    Here is an example of how you can use for_each for a map.

    std::map<int, int> map;
    
    map.insert(std::pair<int, int>(1, 2));
    map.insert(std::pair<int, int>(2, 4));
    map.insert(std::pair<int, int>(3, 6));
    
    auto f = [](std::pair<int,int> it) {std::cout << it.first + it.second << std::endl; };
    std::for_each(map.begin(), map.end(), f);
    
    0 讨论(0)
提交回复
热议问题