Use of for_each on map elements

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

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

    Here this would be:

    for (std::map::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& as an argument instead.

    Example:

    void CallMyMethod(std::pair& 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);
    

提交回复
热议问题