Reputation: 8727
I have a text file that holds values like this:
30 Text
21 Text
12 Text
1 Text
3 Text
I want to read this into a 2D array to keep the number and the text identifier together. Once I've done this I want to sort this into ascending order, as the text file will be unsorted.
What is the best way to go about this in C++, should I put it in an Array? My objective is to just get the top 3 highest values from the text file. Is there a data structure that would be better suited to this or a better way to go about it? I can structure the text file anyway, its not a concrete format if that should be changed.
TIA
Upvotes: 2
Views: 724
Reputation: 82555
If you only want the top three values, the most efficient way may be to define three variables (or a three-element array), read the file line-by-line, and if a newly read line belongs in the top three, put it there.
But if you want to use containers, I'd go with a std::vector
and use std::sort
, assuming that the file is small enough that all the data fits in memory.
Upvotes: 3
Reputation: 319
I would prefer to put them into a std::map (if you have unique keys. If not use a std::multipmap instead.) So as you insert data into the map, they will always be sorted. And if you want to get the 3 highest values, just get the first 3 items of the map.
Upvotes: 2