Insert/read一组成一张图

Insert/read a set into a map

我想 'manage' 航班,使用 map<string, set<string>>string 键代表航班号,而 set<string> 值代表在航班上注册的人名。就我而言,我从一个简单的文本文件中读取数据,例如:

123 jhonny
132 harry
123 bill
145 herry
132 jarry

为了找到同一个航班的人

我知道插入地图的基本方法是

map<string, string> m;
m["hi"] = test;

并使用迭代器读取容器。

但是我怎样才能将集合的组成插入和读取到地图中呢?

我尝试使用双迭代器,或者使用 while 和迭代器从文件中获取数据:

string pers, volo;
while (wf >> volo >> pers) {
    m[volo] = pers;
}

但它给出了错误。

我是 STL 的新手,我已经阅读了一些文件、指南和其他学习集和地图的文件,但我还没有找到任何关于容器组合的信息(比如我描述的那个)。我怎样才能做到这一点?也许在 map 和 set 上使用双迭代器?

谢谢。

就像对待任何一种常规套装一样对待您的 m[volo]。一旦您使用 std::map::operator[]. This allows you to directly use any of set's member functions. To add a value to the set, use std::set::insert.

访问它的值,您的 set 将被默认构造

使用标准 input/output:

您的代码可能如下所示
string a, b;
while (cin >> a >> b) {
    m[a].insert(b);
    cout << m[a].size() << endl;
}

如果你想输出你的集合,一个方便的方法是在 operator<< 上定义一个重载。下面定义一个模板任意集合。

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& s)
{
    for (auto& el : s)
        os << el << ' ';
    return os;
}

这使您可以无误地执行以下操作。

for (auto it = m.begin(); it != m.end(); ++it)
{
    cout << it->first;   // a string
    cout << ' ';
    cout << it->second;   // a set
    cout << endl;
}