In addition to @a.Li's answer, if possible, you can also optimize quite a few things along the way.
Of course, iterating the map twice is probably the least expensive & simple way of solving the issue:
using StringMapType = std::map<std::string, std::vector<std::string>>;
using StringMapVectorType = StringMapType::value_type::second_type;
std::set<StringMapType::key_type> findKeys(const StringMapType &stringMap) {
StringMapVectorType::size_type maximumSize {};
for (const auto &[key, values] : stringMap)
maximumSize = std::max(maximumSize, values.size());
std::set<StringMapType::key_type> results {};
for (const auto &[key, values] : stringMap)
if (values.size() == maximumSize)
results.emplace(key);
return results;
}
However, I would recommend the following, if possible:
- if you aren't interested in ordering the keys in your map type, use std::unordered_map,
- replace the return value type (std::set with std::vector, if you aren't interested in the order of the keys stored in the results.
Object lifetime specific optimizations:
- use std::string_view for the keys you find; this will avoid additional copies of the strings, assuming they aren't optimized out with short string optimization,
- return an array of iterators, instead of their keys
If applied, the code could look something like this:
std::vector<StringMapType::const_iterator> findKeys(const StringMapType &stringMap) {
StringMapVectorType::size_type maximumSize {};
for (const auto &[key, values] : stringMap)
maximumSize = std::max(maximumSize, values.size());
std::vector<StringMapType::const_iterator> results {};
for (auto iterator = stringMap.cbegin(); iterator !=
stringMap.cend(); ++iterator)
if (const auto &values = iterator->second;
values.size() == maximumSize)
results.emplace_back(iterator);
return results;
}
Of course, if you'd like to avoid the whole issue, you can instead sort your values at the time of insertion using a custom comparator, or find the the entry with the most amount of elements in its array, and insert the new entry before it (of course, you'd have to use an unordered map, or another container).
Useful things for the future: