c++ - STL sort doesn't sort my vector<pair<int,int> > well -


i trying solve more complex algorithmic problem , partial requirement involves sorting pairs of integers.

here code ( i've commented irellevant part question)

#include <fstream> #include <vector> #include <queue> #include <algorithm> using namespace std;  ifstream fin("ai.in"); ofstream fout("ai.out");  #define maxn 1001 #define maxk 150001 // //int n; //int t1, t2, s1, s2, s3, s4, r1, r2, r3, r4; int k; int x,y;  vector<pair<int,int> >v(maxk);  int main() { //    fin >> n; // //    fin >> t1 >> t2 >> s1 >> s2 >> s3 >> s4 >> r1 >> r2 >> r3 >> r4;      fin >> k;      ( int = 1; <= k; ++i )     {         fin >> x >> y;         v[i].first = x;         v[i].second = y;     }      sort(v.begin() + 1, v.begin() + n + 1);      ( int = 1; <= k; ++i, fout << '\n' )         fout << v[i].first << ' ' << v[i].second;      fin.close();     fout.close();     return 0; } 

for input

8 1 2 2 3 2 5 4 2 6 2 2 2 2 4 5 2 

i output

1 2 2 2 2 3 2 5 4 2 6 2 2 4 5 2 

which of course wrong can see 2 4 pair near end of output. how can solve this? king regards.

this part of program

fin >> k;  ( int = 1; <= k; ++i ) {     fin >> x >> y;     v[i].first = x;     v[i].second = y; }  sort(v.begin() + 1, v.begin() + n + 1); 

where not clear variable n means

should following way

fin >> k;  if ( maxk < k ) k = maxk;  ( int 0 1; < k; ++i ) {     fin >> x >> y;     v[i].first = x;     v[i].second = y; }  sort( v.begin(), v.begin() + k ); 

the last statement can bewriten like

sort( v.begin(), std::next( v.begin(), k ) ); 

provided header <iterator> included

you may set range [1, k + 1 ) post not clear why frist element of vector should not filled.

it seems unexpected result due setting invalid upper bound of range.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -