XDProgrammer
XDProgrammer

Reputation: 861

sorting a csv file according to column in C++

I been given a task to sort a csv file depending on the users input

The data looks like this:

California,USA,65,76,65,67
Paris,France,78,65,97,87
Tokyo,Japan,56,78,67,87
New York,USA,54,65,67,44,67

Or basically the column represents

City,Country,q1 average temperature, q2 average temperature, q3 , q4

my task is to sort this according to columns: city as column 1, country column 2 , and so on... depending on the user input.

so if the user input is 1dec that means it will be sort by 1st column(alphabetically in this case) and prints the sorted data

for the example above it would print as:

Tokyo,Japan,56,78,67,87
Paris,France,78,65,97,87
New York,USA,65,67,67,44,67
California,USA,65,76,65,67

the user can also enter multiple inputs like 2asc,3dec,4dec this means that, the column 2 will be the first to be sorted in ascending order and if they have similar data in that column, the 3rd column will be use displaying them in descending order, then if its still the same use column 4.

for the example above if called using 2asc,3dec,4dec it would print as:

Paris,France,78,65,97,87
Tokyo,Japan,56,78,67,87
California,USA,65,76,65,67
New York,USA,65,67,67,44,67

My question is, How should I approach this problem? What is the best data structure should I use?

PS. Not really asking for code sample, but I am just asking for some hints or an approach if you will be given this kind of problem

Upvotes: 0

Views: 3180

Answers (2)

Emilio
Emilio

Reputation: 21

My question is, How should I approach this problem? What is the best data structure should I use?

You should use several data structure but if you use a vector to store the input list (and if it is quite big), you'd better to use reserve method so that you'll avoid to reallocate the vector many times.

Another interesting point is to apply repeatedly the ordering criteria in the reverse order so that you'll have the output ordered following the multiple criteria in an easy way.

If you worth about performance you should use a more complex approach.

Upvotes: 0

Johan Engblom
Johan Engblom

Reputation: 215

Here is a method you could use, hope you find it intuitive

  1. Read the data and put it into a unsorted vector with objects (classes) that represents the real world data.
  2. Parse the user input to decide the column and sort order
  3. Use a simple sorting algorithm such as selection sort to add the data to a sorted vector.
  4. iterate over the sorted vector and output the result.

Upvotes: 1

Related Questions