Keep track of highest 5 numbers during file input

2019-05-12 16:57发布

So lets say i have a struct

struct largestOwners
{
    string name;
    double amountOwned;
};

And i am reading it in from a file using ifstream with 300 names and amounts.

How can i go about keeping track of the highest 5 numbers during input? So i dont have to sort after, but rather track it during ifstream input.

My goal is to keep track of the 5 highest amounts during input so i can easily print it out later. And save time/processing rather than to do it in the future

I get i can store this in an array or another struct, but whats a good algorithm for tracking this during ifstream input to the struct?

Lets say the text file looks like this, when im reading it in.

4025025 Tony
66636 John
25 Tom
23693296 Brady
363 Bradley
6200 Tim

Thanks!

7条回答
Luminary・发光体
2楼-- · 2019-05-12 17:22

While reading the file, keep a sorted list of the 5 largest numbers seen (and their owners). Whenever you read a value higher than the lowest of the 5, remove the lowest and insert the new number in your sorted list.

List list can be stored in an array or in any other data structure that has an order and where you can implement a sort and insert. (Or where this is already implemented)

Instead of sorting the list you can also simply go through the 5 entries every time you read a new one (should not be too bad, because 5 entries is a very small number)

查看更多
登录 后发表回答