Tuesday, 8 December 2020

Iterating through std::maps

 Map Iterators in C++17

I'm not going to comment on whether it is right or wrong to iterate through a map but bear in mind that there are other containers that are faster to iterate through.

This snippet shows the 3 ways I know to iterate through a map and the syntax to use the data. Note that the named pair is only available since C++17.

class MyClass
{
public:
    std::map<intint> m_map;
    MyClass():
        m_map{}
    {
    }
    void Print(const int a, const int b)
    {
        std::cout << "\ta:" << a << " b:" << b << std::endl;
    }
    void Run()
    {
        m_map[1]=2;
        m_map[2]=4;

        std::cout << "Iterator:\n";
        for (auto it = m_map.begin(); it != m_map.end(); it++)
        {
            Print(it->first, it->second);
        }

        std::cout << "Auto pair:\n";
        for (auto pr : m_map)
        {
            Print(pr.first, pr.second);
        }

        std::cout << "Named pair:\n";
        for (auto& [a,b] : m_map)
        {
            Print(a, b);
        }
    }
    /* prints:
        Iterator:
            a:1 b:2
            a:2 b:4
        Auto pair:
            a:1 b:2
            a:2 b:4
        Named pair:
            a:1 b:2
            a:2 b:4
    */
};

No comments:

Post a Comment