打印作为集合的无序映射的第二个元素

Printing the second elements of an unordered map that is a set

我有一个简单的问题,如果我有 std::unordered_map<std::string, std::set<std::string> > h; 我如何打印出该集合 h 的第二个元素?

我知道第一个元素我们可以说

for (auto it : h) {
    std::cout << "First: " << it.first << " ";
}

虽然同样不适用于it.second

Error: error C2679: binary '<<': no operator found which takes a right-hand operand of type '_Ty2' (or there is no acceptable conversion)

迭代并打印集合元素。

for (auto& level1 : h) {
    std::cout << "First: " << level1.first << " Second:";
    for (auto& set_element : level1.second) {
        std::cout << set_element << " ";
    }
}

如果你真的想使用level1.second,重载<<运算符

ostream & operator << (ostream &out, const std::set<std::string> &myset) 
{ 
    for (auto& set_element : myset) {
        out << set_element << " ";
    }
    return out; 
} 

并使用

for (auto& level1 : h) {
    std::cout << "First: " << level1.first << " Second:"<<level1.second;
}

first是一个字符串,所以可以打印出来。 second 是一个 set 字符串。你不能只计算集合,你必须打印一个字符串 inside 集合。

it->second.begin() 应该给你指向集合第一个元素的迭代器。