2013-02-27 71 views
0

我知道External merge sort以及它是如何工作的。 但目前我卡住实施它。我写的代码进行排序和合并的阵列,但我现在面临的问题,同时读取和/数据写入到文件,我想实现在C++以下方法:实现外部合并排序

1. int * read(int s, int e) : This method should read from file all the number 
starting from 's' till 'e' and return the array 
2. write(int a[], int s, int e) : This method should write to file the input 
array by replacing the numbers from s to e. 

对于如。

Given file has the following numbers: 

1 
2 
3 
4 
5 
6 

read(0, 2) should return [1,2,3] 
write([4,5,6], 0, 2) should update the file to : 
4 
5 
6 
4 
5 
6 

我该如何实现这两种方法?

回答

1

你应该做的第一件事就是停止使用原始指针。

std::vector<int>将一样高效,而且更不容易出错。

其次,文件格式很重要。我将假设一个带有32位有符号整数的二进制文件。

用于读取和写入签名现在是:

std::vector<int> read(std::ifstream const& f, int offset); 
void write(std::ofstream& f, int offset, std::vector<int> const& data); 

ifstreamofstream有寻求方法 - 尤其是ifstreamseekgofstreamseekp

ifstream.read(char* , length)从当前获取位置处的文件读取length字节(由seekg设置,并且由read提前)。如果您不关心文件的内存布局,可以从std::vector<int>获取.data(),将其重新解释为char*,然后继续执行read(reinterpret_cast<char*>(vec.data()), sizeof(int)*vec.size())以一次性读入缓冲区。

ofstream有一个类似的write方法,其工作方式非常相似。在大多数(每个?)实现中,将数据写入磁盘并写回数据是危险的,但在同一个执行会话(甚至可能在会话之间)写入和读取数据时,您将可以安全使用数据。如果数据意图在会话之间持续存在,或者从代码输出/输入,请多加小心。

0

没有C++标准函数跳转到文件中的行。所以你必须逐行读取文件(例如使用getline,例如http://www.cplusplus.com/reference/string/string/getline/)。

据我所知,外部合并排序(旧的,用于带有几个磁带驱动器的计算机)与单独的文件一起使用时,不需要类似于您的界面 - 您可以顺序工作。

+0

正如Yakk所说,通过使用istream :: seekg和istream :: tellg函数,可以跳转到文本文件中的一行。但是,我不确定这些功能的时间复杂性和效率。 请参阅以下链接中的示例:http://www.cplusplus.com/reference/istream/istream/seekg/ – 2016-04-21 21:47:11