How to filter items from a std::map in C++

1 Answer

0 votes
#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> mp = {{1, "a"}, {2, "ab"}, {3, "abc"}, {4, "abcd"}, {5, "abcde"}};
    std::map<int, std::string> filteredMap;

    auto filterCondition = [](const std::pair<int, std::string>& item) {
        return item.first % 2 == 0; // filter when key is even
    };

    for (const auto& item : mp) {
        if (filterCondition(item)) {
            filteredMap[item.first] = item.second;
        }
    }

    for (const auto& item : filteredMap) {
        std::cout << item.first << ": " << item.second << std::endl;
    }
}


 
/*
run:

2: ab
4: abcd

*/

 



answered Jan 21 by avibootz

Related questions

1 answer 33 views
1 answer 44 views
2 answers 115 views
3 answers 90 views
...