good afternoon.
i ran problems. can solve it, have little experience in programming, , seems me there more beautiful , rational solutions problem.
the problem follows. given set of text files total size of more 1 hundred megabytes. number of files 2 n. files contain sorted unique numbers (for example, ids). wanted merge numbers in 1 output file. inside resulting file numbers need sorted.
i'm going solve problem follows: open files. take out first number of each file. put them in container (eg, vector). find smallest number within container. put minimal number in output file. in place, put following number file, taken minimal number. seems method called "external merge sort".
tell me, please, there smarter way solve problem?
external mergesort created exact problem. complexity of sort n * log(number_of_files).
for simplicity in code can store filestreams along numbers in priority queue.
completely untested, maybe helpful code:
std::vector<ifstream> file_streams(stream_count); // open streams. using int_and_stream = std::pair<int, std::ifstream&>; using cont = std::vector<int_and_stream>; std::priority_queue<int_and_stream, cont, pair_comparer> queue; for(auto& stream: file_streams){ int id; stream >> id; queue.push(std::make_pair(id, stream)); } while(!queue.empty()){ auto smallest = queue.top(); outstream << smallest.first; int id; if(smallest.second >> id){ // file ended? queue.push(std::make_pair(id, stream)); } } for pair_comparer can here
Comments
Post a Comment