【问题标题】:How to remove similiar values and group it from a text file in c++?如何从 C++ 中的文本文件中删除相似值并将其分组?
【发布时间】:2020-06-26 18:21:08
【问题描述】:

假设我有一个文本文件

200     34

34     377

20      2

34     45

200    7

10     63

我想以不重复第一列的值并包含第 2 列的元素的方式对其进行分组,如下所示:

200:  34  7


34 :  377 45


20:   2


10:   63

我该怎么做?我是一名初学者程序员,到目前为止,我只设法读取文件并将其打印出来,就像使用

ifstream inFile;

inFile.open("textfile.txt");

if (inFile.fail()) {
    cerr << "Error opeing a file" << endl;
    inFile.close();
    exit(1);
}
string line;

while (getline(inFile, line))
{
    cout << line << endl;
}

inFile.close();

【问题讨论】:

    标签: c++ file grouping computer-science


    【解决方案1】:

    将输入读入多重映射,然后遍历输入的元素。

    std::multimap<int, int> m;
    int a, b;
    while (inFile >> a >> b) {
        m.insert(std::make_pair(a, b));
    }
    inFile.close();
    
    
    for (auto it = m.begin(); it != m.end(); ) {
        std::cout << it->first << ": ";
        for (auto end = m.upper_bound(it->first); it != end; it++) {
            std::cout << it->second << " ";
        }
        std::cout << "\n";
    }
    

    但也许只考虑带有矢量的地图会更容易:

    std::map<int, std::vector<int>> m;
    int a, b;
    while (inFile >> a >> b) {
        m[a].push_back(b);
    }
    inFile.close();
    
    for (auto i : m) {
        std::cout << i.first << ": ";
        for (auto j : i.second) {
            std::cout << j << " ";
        }
        std::cout << "\n";
    }
    

    Tested on godbolt.

    您的输出似乎有相反顺序的键,因此您可以使用带有反向迭代器的 rbeginrend 来迭代地图。

    【讨论】:

    • 第二个中的while循环可以简化很多...while (inFile &gt;&gt; a &gt;&gt; b) { m[a].push_back(b); }
    • 好吧,因为m[a] 会插入不存在的密钥。
    • 示例输出也可能按第一次出现的键排序,而不是降序。
    • 哦,我明白了!是的,地图更容易理解。尽管对于 stringstream inFile 的代码部分,有没有办法不对值进行硬编码?因为我们假设我给出的值来自一个文本文件
    • 我只在godbolt中使用stringstream进行测试。您在代码中使用ifstream
    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多