C++ STL/Map; Print entries with certain condition

From Software Engineers Wiki
Jump to: navigation, search

With std::map<std::string, int> pair, print entries with int value under 3.

Answer

Using iterator

#include <iostream>
#include <algorithm>
#include <map>

int main(void)
{
        std::map<std::string, int> emp = {
                { "Name0", 0 },
                { "Name1", 1 },
                { "Name2", 2 },
                { "Name3", 3 },
                { "Name4", 4 },
                { "Name5", 5 },
        };
        std::map<std::string, int>::iterator it;

        for (it = emp.begin(); it != emp.end(); ++it) {
                if (it->second < 3)
                        std::cout << it->first << " " << it->second << std::endl;
        }

        return 0;
}

With result

Name0 0
Name1 1
Name2 2

It is possible to use std::for_each(). for_each() takes a unary function. The unary function can take "const T &" as parameter.

void check_3(const std::pair<std::string, int> &e)
{
        if (e.second < 3)
                std::cout << e.first << " " << e.second << std::endl;
}

int main(void)
{
        std::for_each(emp.begin(), emp.end(), check_3);
}

Or it may have the unary function take "T" as parameter which invokes a copy constructor.

void check_3_value(std::pair<std::string, int> e)
{
        if (e.second < 3)
                std::cout << e.first << " " << e.second << std::endl;
}

int main(void)
{
        std::for_each(emp.begin(), emp.end(), check_3_value);
}

Or you may use lambda function

int main(void)
{
        std::for_each(emp.begin(), emp.end(), [](std::pair<const std::string, int> &e) { if (e.second < 3) std::cout << e.first << " " << e.second << std::endl; });
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox