从一个文件和另一个单独的文件中取出时间,并将两个文件中的时间值放入c++列表中

Take time from one file and another separate file and place the time values from both files into a list c++

本文关键字:文件 时间 两个 列表 c++ 一个 另一个 单独      更新时间:2023-10-16

我正在尝试加载两个文件,但是我很难将文件1文件2中输入的时间,并将它们放入包含所有时间的列表中,但如果时间已经输入,则不会再次输入。

这不是家庭作业。我只是在自己做一个应用程序项目。

——我建立了一个时间列表,在一个集合中的每个文件,然后加载的时间已经被放置到一个地图只有一个列表的时间,但我不知道从哪里开始。明白了吗?

简单地读取文件,在(un)ordered_map中插入读取的次数,如果要插入的条目已经添加,则跳到下一个迭代。

#include <unordered_map>
std::unordered_map<std::string, VALUE_TYPE> hash;
while (read line) {
    std::string date(extract_date(line));
    auto it(hash.insert(std::make_pair(date, VALUE_TYPE())));
    // If you want to check whether the last value has been inserted
    if (it.second) {
        // do something with the pair it.first
    }
}

:

map中,无论是否有序,您都在映射值,因此,对于每个A类型的值,您将保存一些B类型的值。

在这种情况下,一旦您必须为每个日期保存一些VALUE_TYPE值,您可以简单地获取时间字符串,将其视为一个键,并且,如果键已经添加到映射容器中,则不会再次插入它—将保留在容器中的VALUE_TYPE值将是初始值。

std::map<int, int> map;
map.insert(std::make_pair(1, 1));
map.insert(std::make_pair(2, 1));
map.insert(std::make_pair(1, 2));
map.insert(std::make_pair(2, 2));
for (auto it(map.begin()); it != map.end(); ++it) {
    std::cout << it->first << " " << it->second << std::endl;
}
输出:

1 1
2 1

如果时间值在文件中排序,则最好使用std::list<time>来完成任务。将file1和file2中的值按顺序读入不同的列表中,并按此顺序使用list::mergelist::unique。这是因为std::setstd::map都不保留它们存储的值的顺序。

您需要使用list::push_back, list::merge和list::unique,并且每个文档页面都包含一个示例。