如何使用C++中的堆栈、队列或 BST 对文件中的记录进行排序
How to sort records in a file using a stack, queue, or BST in C++?
如果您有包含以下记录的.dat文件:
805816899 Andrew
803975268 Bob
912684297 Jeff
123546789 Louis
751354687 Kevin
为了按 ID 号对列表进行排序然后写入屏幕,最容易使用的数据结构是什么?我认为 BST 最有意义且效率最高,但是在处理这样的小文件时,堆栈会更容易、更快捷。
另外,您将如何实现它?
最简单的方法是使用 BST 对它们进行排序,就是将它们放在std::map<int, std::string>
中。这是一种在内部使用 BST 的自排序数据结构(尽管标准没有明确指定)。如果不想查找,可以改用用户定义类型的std::set
(请参阅下一段)。
一个扁平的类似数组的结构中,你可以创建一个小结构来保存信息,将其实例存储在std::vector
中,并使用合适的比较函数与std::sort
结合使用来进行排序。
英国夏令时:
#include <string>
#include <map>
std::map<int, std::string> m;
m[805816899] = "Andrew";
m[803975268] = "Bob";
等等。
类似阵列的解决方案:
struct Foo
{
Foo(int ID, const std::string& name) : ID(ID), name(name) {}
int ID;
std::string name;
};
// comparison for sorting
bool comp(const Foo& lhs, const Foo& rhs) { return lhs.ID < rhs.ID; }
#include <vector>
#include <algorithm>
....
std::vector<Foo> v;
v.push_back(Foo(805816899, "Andrew"));
v.push_back(Foo(803975268, "Bob"));
// add more entries
std::sort(v.begin(), v.end(), comp);
我认为,trie 是实现整个排序的最简单方法,如果 id 的长度恒定,则为 O(n)。
#include <iostream>
#include <cassert>
#include <string>
class node {
bool final;
union {
node *next[10];
char *name;
};
node *get_at(int index)
{
assert(!final);
return next[index] ? next[index] : (next[index] = new node);
}
public:
node() : final(false) { std::fill(next, next+10, (node*)0); }
~node() {
if (final)
delete name;
else
for (int i=0; i<10; ++i)
delete next[i];
}
void insert(const char *id, std::string const& s)
{
if (*id) {
get_at(*id - '0')->insert(id+1, s);
} else {
final=true;
name = new char[s.size()+1]();
std::copy(s.begin(), s.end(), name);
}
}
void print_all(std::ostream& os) const
{
if (final)
os << name << 'n';
else
for (int i = 0; i < 10; ++i)
if (next[i])
next[i]->print_all(os);
}
};
int main()
{
node top;
for (std::string id, name; std::cin >> id >> name;)
top.insert(id.c_str(), name);
top.print_all(std::cout);
}
相关文章:
- 创建 Spdlog 异步文件记录器时遇到困难
- 分段错误:从文件中访问csv记录时转储了核心
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- c++ - 将大文件记录处理到 cpp 容器的最有效方法
- GDB / C++ - 根据循环条件将多个变量记录到输出文件中
- 在OSX中使用CGDisplayStream存储屏幕记录的特定文件路径
- 如何在文本文件中搜索员工记录(按名称)并仅显示其详细信息?
- 在二进制文件中删除记录
- C++同时记录到控制台和日志文件
- 如何让 doxygen 记录 .tcc 文件中定义的模板类?
- 为什么 fstream 打印出文件的最后一条记录
- QT控制台:记录所有stdin和stdout要文件
- 文件仅读取1个记录,然后到达文件的末尾,即使还有其他记录
- 将记录添加到文件中并将其读回
- C - 如何在文本文件中搜索学生记录
- 在特定字段中关键字搜索后,从文本文件中提取多个记录
- C 11中线程之间的共享文件记录
- 在数据库文件中创建10条空白记录
- 控制台/文件记录器库C++
- C++我的文件记录器类有什么问题?