Use of for_each on map elements

前端 未结 11 731
北荒
北荒 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
    闹比i (楼主)
    2021-01-30 11:12

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

    std::map 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.

提交回复
热议问题