Sorting a list

I have a .txt file which I want to read from and then write a new text file, this time with sorted lines. It is easy to sort one value, but what about sorting entire lines based on one value?

I want to sort the lines based on the FIRST value.

Example text file contents:
1
2
3
4
5
6
values;data
5.01 100
2.9 342
2.69 43534
10.1 43
6.8 45324


Output: Text file containing
1
2
3
4
5
2.69 43534
2.9 342
5.01 100
6.8 45324
10.1 43


It's easy to do this if there was only 1 number on each line, but I do I sort all the lines based on the first number in each line?
If this is a unix system, just do sort -n < file.txt

If you have to write the code, then you need a class with two members: the number and the string. Add operator < that works on the number. Now read the files, populate an instance of your class and drop it into a std::set. When you're done, just iterate over the set and write them out. This will work because sets are ordered.
What if there are duplicate lines, (or duplicate first values), the std::set will omit duplicates, won't it?

However, there is a std::sort which can work with a std::vector, might be better to use that than a set.
Last edited on
Topic archived. No new replies allowed.