-2

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

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

--我正在构建一个时间列表,该列表将每个文件放在一个集合中,然后将已放入地图的时间加载为只有一个时间列表,但我不知道从哪里开始。如果这有意义吗?

4

2 回答 2

1

只需读取文件,插入读取的时间(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
    }

}

说明

在 amap中,无论是否有序,您都在映射值,因此,对于 type 的每个值A,您将保存一些 type 的值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
于 2013-04-17T11:52:19.517 回答
0

如果时间值在文件中排序,则std::list<time>用于该任务可能会更好。将 file1 和 file2 中的值按排序顺序读取到不同的列表中,并按此顺序使用list::mergelist::unique。这是因为既不std::set,也不std::map保留它们存储的值的顺序。

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

于 2013-04-17T11:54:10.193 回答