Kitchi
Kitchi

Reputation: 1904

Sorting a file based on first array element

I have a (binary) file which has multiple entries of an array of 6 elements. So the file would be structured something like this :

{1 2 12 18 22 0} {11 17 20 19 20 7} {3 9 18 24 0 9}...

where I have put brackets around the elements that form one array. I'd like to sort the file based only on the first element of each array, so the sorted file should read

{1 2 12 18 22 0} {3 9 18 24 0 9} {11 17 20 19 20 7}...

How would I go about doing this?

Upvotes: 2

Views: 81

Answers (2)

Emu
Emu

Reputation: 5905

#include<stdio.h>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;

int main () {

    vector < vector<int> > v;
    vector <int> t;

    t.push_back(4);
    t.push_back(5);
    t.push_back(6);
    v.push_back(t); 
    t.clear();
    t.push_back(1);
    t.push_back(2);
    t.push_back(3);
    v.push_back(t);

    sort(v.begin(),v.end());

    for (int i = 0; i < v.size(); i++){
        for (int j = 0; j < v[i].size(); j++){
             cout << v[i][j] << " ";
        }
        cout << endl;
    }



    return 0;

}

Upvotes: -1

user694733
user694733

Reputation: 16043

  1. Read file into 2 dimensional array. Each element on the first dimension should hold six elements.
  2. Implement comparison function for qsort.
  3. Use qsort with your comparision function to sort the array.
  4. Write array back to file.

Upvotes: 2

Related Questions