Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements from map<key, set<datatype>>

Tags:

c++

c++11

set

map

I am working with a data structure that looks like this:

map<string, set<string>> data;

By now, I had no problems with working with the map by using foreach cycle, however, now I need to print out the data from the map like this:

KEY: elem1, elem2, elem3
KEY2: elem1, elem2, elem3

Because of the missing comma at the end, I cannot quite use the foreach cycle anymore (can I?). Since I am new to C++, C++11 and all the fun it offers, I am quite lost. I came up with:

for ( auto i : data )
{
    cout << i.first << ": ";
    for ( size_t i = 0; i < /* size of the set */ - 1; i ++ )
        cout << j << ", ";

    cout << /* the last element of the set */ << endl;
}

I know what I want, I just have no idea about syntax and the C++ reference is not helping much. Thanks for answers, meanwhile I am going to browse the C++ reference myself.

like image 540
Lea Avatar asked Mar 09 '14 14:03

Lea


1 Answers

A pattern I often use (with BOOST_FOREACH), is:

bool first = true;
for (auto const& e: collection) {
    if (first) { first = false; } else { out << ", "; }
    ...
}

There is a STL way of doing this though, using ostream_iterator:

std::copy(collection.begin(), collection.end(),
          std::ostream_iterator<value_type>(out, ", "));

and so your example becomes:

for (auto const& pair: map) {
    out << pair.first << ": ";

    std::copy(pair.second.begin(), pair.second.end(),
              std::ostream_iterator<std::string>(out, ", "));
}

but honestly, I still feel like using the bool first = true approach is more readable.

like image 130
Matthieu M. Avatar answered Oct 14 '22 17:10

Matthieu M.