c++ - Sorting arrays difficulty -
i need process data input file has max. 100,000 lines following:
2014269619 sally clare smith female 95
these id number, name (2 or 3 words), gender , exam score. separated tabs.
i must create array of max. 100,000 length each of these attributes. also, first number within input file number of lines in file. so, create arrays length 100,000.
once set array, use given function sort names alphabetical string order (ascending) of name , put these output file. however, not required use specific function.
my challenge here although given function sorts names, not move id, gender, , score names, resulting in useless database.
i have tried doing first part (setting arrays) in following way seems wrong:
#include <iostream> #include <fstream> using namespace std; void ordering_sort( double x[], int length) { int i, j, k; double t; (i=0; i<length-1; ++i) { k = i; //find next smallest elm, x[k] (j=i+1; j< length; ++j) if (x[k] > x[j]) k = j; //swap x[i] x[k] t = x[i]; x[i] = x[k]; x[k] = t; } } int main () { ifstream fin; ofstream fout; fin.open("input.txt"); fout.open("output.txt"); if (fin.fail()) { cout << "fail open inout.txt" << endl; exit(1); } int id [100000]; string name [100000]; string gender [100000]; int score [100000]; int y = 0; // in following part, trying extract information different arrays, // 1 one, increasing number of element 0 till x. // problem getline not work int arrays must use int. (int y=0 ; y<x, y++) { getline(fin, id [y], '\t'); // not work. getline(fin, name [y], '\t'); getline(fin, gender [y], '\t'); getline(fin, score [y], '\t'); //this not work either. break; } ordering_sort( name, int length) // trying use function, not work of basically, need with:
- extracting data input file arrays making sure sorting apply every line not individual arrays (so whole lines sorted)
- finding way make getline work int arrays
- i shall output data output file should not problem.
- all of must done using arrays , without using structures, vectors, maps.
other libraries fine.
technically speaking, code not valid standard c++, relies on compiler extensions (in particular gcc style ones)
int id [x]; string name [x]; string gender [x]; int score [x]; so, make valid standard code, have use new. i'm going ignore that, expect shown code compiles , that's enough project.
- finding way make getline work int arrays
since items separated tabs (from can tell), need is:
cin >> id[y]; getline(cin, name[y], '\t'); ... cin >> score[y]; as sorting part, there 2 solutions:
- as suggested in comment, sort index-table.
- in sort function, when swap, swap items.
the sorting of index table this:
if (score[index[i]] > score[index[j]]) swap(index[i], index[j]); the swap apprach this:
if (score[i] > score[j]) { swap(id[i], id[j]); swap(name[i], name[j]); swap(gender[i], gender[j]); swap(score[i], score[j]); }
Comments
Post a Comment