I’m doing some programming practice right now by trying to sort a 2D array on it’s first “column”.
I am reading input from a file:
100 5
8 80
5 20
9 40
3 10
6 30
This is my code:
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
bool helper(vector<long> k, vector<long> l)
{
return (k[0] < l[0]);
}
int main()
{
ifstream fi("milk.in");
ofstream fo("milk.out");
long price = 0, n, m, i, p, a;
vector< vector<long> > farmers;
vector<long> farmer(2,0);
fi >> n >> m;
for (i=0; i<n; ++i)
{
fi >> p >> a;
farmer[0] = p;
farmer[1] = a;
farmers.push_back(farmer);
}
sort(farmers.begin(),farmers.end(),helper);
for (i=0; i<m; ++i)
{
cout << farmers[i][0] << " " << farmers[i][1] << endl;
}
return 0;
}
As you can see, I try to sort the input by it’s first column (I don’t care about the first line at the moment).
However, this is the result:
3 10
5 20
6 30
6 30
6 30
This is the expected result:
3 10
5 20
6 30
8 80
9 40
I can’t figure it out.
Your first line of your
milk.in:You’re going to end up looping through trying to read in 100 inputs from this file because n = 100.
If you change milk.in to:
That seems to work.
Perhaps a better idea is to just check if you’re done reading input from the filestream: