[英]Sort integers from text file in C++
正确,因此我设法使程序连接两个文本文件,现在我需要对创建的文本文件进行排序,以便它们以数字顺序显示。 例如,假设Test1.txt包含数字1,2,3,4,5,而Test2包含数字4,5,6,8,myoutput.txt应该具有1,2,3,4,4,5,5, 6,8。 我对排序算法不是很熟悉。 我猜我将不得不读取输出文件,对它们进行排序,然后再次写入输出文件。
这是我当前的代码:
#include <iostream>
#include <fstream>
#include <ostream>
using namespace std;
int main()
{
//collecting integers from first text file//
ifstream file1("test1.txt", ios::in | ios::binary);
if(!file1)
{
cout << "Cannot open input test file 1.\n";
return 1;
}
// collecting integers from second text file//
ifstream file2("test2.txt", ios::in | ios::binary);
if(!file2)
{
cout << "Cannot open input test file 2.\n";
return 1;
}
//outputting the concactonated file to myoutput.txt//
ofstream cout("myoutput.txt", ios::out | ios::binary);
if(!cout)
{
cout << "can't open output file ";
return 1;
}
cout << file1.rdbuf();
cout << " " << flush;
cout << file2.rdbuf();
ifstream sortfile("myoutput.txt, )
return 0;
}
将单个数字读取为整数,将其压入std :: vector ,然后使用std :: sort对其进行排序,然后将其写入输出文件。 这些步骤中的每一步都是微不足道的,并且涵盖了许多SO问题。
您应该对这样的文件中的排序数组使用合并排序。 在http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/mergeSort.htm上查看合并排序算法。 以及位于http://www.c.happycodings.com/Beginners_Lab_Assignments/code27.html的示例源代码
我认为在这种情况下最好使用tp合并排序。 从两个文件中读取一个数字,将它们进行比较,然后将最小的数字插入输出文件。 通过这种方法,我认为时间复杂度会降低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.