Last active
August 29, 2015 13:57
-
-
Save airekans/9797124 to your computer and use it in GitHub Desktop.
Use a heap to merge multiple files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef pair<int, int> Elem; | |
bool compare(const Elem& lhs, const Elem& rhs) | |
{ | |
return lhs.first < rhs.first; | |
} | |
int main() | |
{ | |
vector<ifstream*> files; | |
vector<Elem > heap; | |
for (int i = 0; i < files.size(); ++i) | |
{ | |
int num = 0; | |
if ((*files[i]) >> num) | |
{ | |
heap.push_back(make_pair(num, i)); | |
} | |
} | |
make_heap(heap.begin(), heap.end(), compare); | |
ofstream os("out.txt"); | |
while (!heap.empty()) | |
{ | |
const Elem top = heap.front(); | |
os << top.first << endl; | |
pop_heap(heap.begin(), heap.end()); | |
heap.pop_back(); | |
int num = 0; | |
if (*files[top.second] >> num) | |
{ | |
heap.push_back(make_pair(num, top.second)); | |
push_heap(heap.begin(), heap.end()); | |
} | |
} | |
for (int i = 0; i < files.size(); ++i) | |
{ | |
delete files[i]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment