jeudi 4 juillet 2019

How to print a range belonging to a map (not all elements)

How can I print a range of elements (key and value) belonging to a std::map<size_t, std::string>?
I don't need to print all elements.
Every suggestion using C++11, C++14 or C++17, without boost libraries, is appreciated.

#include <iostream>
#include <iomanip>
#include <string>
#include <map>

using namespace std;

void print(map<size_t, string> & m)
{
    for(auto & [key, value] : m)
    {
        cout << setw(6) << left << key << value << endl;
    }
}

void print_range(map<size_t, string> & m, size_t first, size_t last)
{
    // ???
}

int main()
{
    map<size_t, string> data {
                                { 5, "guitar" },
                                { 8, "saxophone" },
                                { 28, "trumpet" },
                                { 32, "trombone" },
                                { 42, "violin" },
                                { 45, "viola" },
                                { 48, "cello" },
                                { 52, "double bass" },
                                { 100, "piano" },
                                { 104, "drum" }
                             };

    print(data);
    print_range(data, 42, 52);    // ???

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire