2

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

James MV
  • 8,569
  • 17
  • 65
  • 96
  • see this question http://stackoverflow.com/questions/10376411/how-do-you-split-a-string-read-from-a-file-into-arrays-in-c – Vijay Apr 30 '12 at 12:28

2 Answers2

3

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.

Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
2

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.

phantasmagoria
  • 319
  • 1
  • 5