0

I have a task to fill empty std::map<char, std::set<std::string>> myMap, by an array

const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };

and print it using range based for and bindings. Result, should be like S: sun, surprise

The last one(printing) I have already implement in this way

for (const auto& [k, v] : myMap)
{
    cout << "k = " << k << endl;
    std::set<std::string>::iterator it;
    for (it = v.begin(); it != v.end(); ++it)
    {
        cout << "var = " << *it << endl;
    }
}

But how can I initilase this map, by const char* s[] in right way?

P.S. I know, how to initialize it like std::map<char, std::set<std::string>> myMap = { {'a', {"abba", "abart", "audi"} } }; and I read this and this posts on StackOverflow, but I am still have no idea, how to do this by this array.

2
  • 1
    a map contains keys and mapped values, it isnt obvious how the array should be filled to the map Commented Nov 10, 2020 at 16:37
  • OT: Why don't you use a range-for loop for printing the set as well? Commented Nov 10, 2020 at 16:43

1 Answer 1

3

How about this?

const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
std::map<char, std::set<std::string>> myMap;

for (auto str : s)
    myMap[str[0]].insert(str);

// Result: {
//     'a' -> {"alpha", "apple", "asteriks"},
//     'c' -> {"car"},
//     's' -> {"sun", "surprise"}
// }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.