在网上偶然看到一道题目,发现博主的答案有问题,所以重新解答一下题目 原题链接【https://blog.csdn.net/qq_29108585/article/details/60956567】 在这里插入图片描述


#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

static vector<pair<string, int>> file;

void preReadFile()
{
    ifstream fin ( "case.txt" );
    string line;
    string line_sign;
    int line_data;
    stringstream ss;
    while ( ss.clear(), ss.str ( "" ), getline ( fin, line ) )
    {
        ss << line;
        ss >> line_sign;
        ss >> line_data;
        file.push_back ( make_pair ( line_sign, line_data ) );
        // cout << ss.str() <<"|"<< line_sign << "|" << line_data << endl;
    }
}

typedef int CATEGORY;
typedef set<int> DATA;

map<CATEGORY, DATA> LEVEL_1, LEVEL_2;
void parseFile()
{

    CATEGORY pre_lv1_category = 0;
    CATEGORY pre_lv2_category = 0;
    for ( int i = 0; i < file.size(); ++i )
    {
        auto &cur_category = file[i].first;
        auto &cur_data = file[i].second;
        // cout << cur_category << "|" << cur_data << endl;
        if ( cur_category == "#" )
        {
            pre_lv1_category = cur_data;
            LEVEL_1.insert (make_pair (pre_lv1_category, set<int>()));

        }
        else if ( cur_category == "##" )
        {
            pre_lv2_category = cur_data;
            LEVEL_1[pre_lv1_category].insert (cur_data);
            LEVEL_2.insert (make_pair (pre_lv2_category, set<int>()));

        }
        else if ( cur_category == "*" )
        {
            LEVEL_2[pre_lv2_category].insert (cur_data);
        }
        else
        {
            cout << "Parse Error" << endl;
        }
    }
}

int main ( int argc, const char **argv )
{
    preReadFile();
    parseFile();
    for ( auto it1 = LEVEL_1.begin(); it1!=LEVEL_1.end(); ++it1 )
    {
        cout << "# " <<it1->first << endl;
        for (auto it2 = it1->second.begin(); it2!=it1->second.end(); ++it2)
        {
            cout << "## " <<*it2 << endl;
            for (auto it3 = LEVEL_2[*it2].begin(); it3!=LEVEL_2[*it2].end(); ++it3)
            {
                cout << "* " <<*it3 << endl;
            }

        }
    }

    return 0;
}


运行结果: 在这里插入图片描述


测试文件(case.txt):

# 1
## 33
* 506
* 809
# 2
## 4600
* 132
* 2345
## 5960
* 34
# 1
## 33
* 506
* 506


备份地址: 【[重新解答]阿里笔试:去重和排序,重新输出Markdown格式