【问题标题】:Insert/read a set into a map将集合插入/读取到地图中
【发布时间】:2019-01-23 12:19:46
【问题描述】:

我想使用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 的新手,我已经阅读了一些文件、指南和其他文件来学习集合和地图,但我还没有找到任何关于容器组合的内容(例如我所描述的那个)。我怎样才能做到这一点?也许在地图和片场使用双迭代器?

谢谢。

【问题讨论】:

    标签: c++ dictionary stl set composition


    【解决方案1】:

    只需像对待任何常规集合一样对待您的m[volo]。一旦您使用std::map::operator[] 访问它的值,您的set 将被默认构造。这允许您直接使用set 的任何成员函数。要向集合中添加值,请使用 std::set::insert

    这是您的代码使用标准输入/输出时的样子:

    string a, b;
    while (cin >> a >> b) {
        m[a].insert(b);
        cout << m[a].size() << endl;
    }
    

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

    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;
    }
    

    【讨论】:

    • 啊,好的,它似乎可以工作,谢谢(尽管我不明白方法是如何工作的)。并阅读它?我尝试使用 '''map>::iterator iter = m.begin(); for (; iter != m.end(); ++iter) { cout first second
    • @Romans 你的代码和错误描述应该在your question 但没关系。 iter-&gt;second 的类型是 set,不是吗? cout 不知道如何处理。您可能需要使用set::iterator 的第二个循环。 (您也可以定义一个接受std::sets 的operator&lt;&lt;,但这可能有点挑战性。)
    • @TrebuchetMS 在coliru.stacked-crooked.com 的默认程序有一个&lt;&lt; 对应vector,你可以把set 换成那个
    猜你喜欢
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2012-10-20
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    相关资源
    最近更新 更多