Skip to content

Instantly share code, notes, and snippets.

@airekans
Last active August 29, 2015 13:57
Show Gist options
  • Save airekans/9797124 to your computer and use it in GitHub Desktop.
Save airekans/9797124 to your computer and use it in GitHub Desktop.
Use a heap to merge multiple files.
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