简体   繁体   English

STL 排序不对我的向量进行排序<pair<int,int> &gt; 好吧

[英]STL sort doesn't sort my vector<pair<int,int> > well

I am trying to solve a more complex algorithmic problem and a partial requirement involves sorting some pairs of integers.我正在尝试解决一个更复杂的算法问题,部分要求涉及对一些整数对进行排序。

Here is my code ( I've commented the irellevant part for my 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;

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

    sort(v.begin() + 1, v.begin() + n + 1);

    for ( int i = 1; i <= k; ++i, fout << '\n' )
        fout << v[i].first << ' ' << v[i].second;

    fin.close();
    fout.close();
    return 0;
}

For this input对于这个输入

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

I get this output我得到这个输出

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

Which of course is wrong as you can see the 2 4 pair near the end of output.这当然是错误的,因为您可以在输出末尾附近看到 2 4 对。 So how can I solve this?那么我该如何解决这个问题呢?

This part of the program这部分程序

fin >> k;

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

sort(v.begin() + 1, v.begin() + n + 1);

where it is not clear what variable n means不清楚变量n含义

Should look the following way应该看下面的方式

fin >> k;

if ( MaxK < k ) k = MaxK;

for ( int i 0 1; i < k; ++i )
{
    fin >> x >> y;
    v[i].first = x;
    v[i].second = y;
}

sort( v.begin(), v.begin() + k );

The last statement can bewriten also like最后一条语句也可以写成

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

provided that header <iterator> will be included前提是标题<iterator>将被包括在内

You may set also the range like [1, k + 1 ) but from your post it is not clear why the frist element of the vector should not be filled.您也可以设置像 [1, k + 1 ) 这样的范围,但是从您的帖子中不清楚为什么不应该填充向量的第一个元素。

It seems that you get an unexpected result due to setting invalid upper bound of the range.由于设置了无效的范围上限,您似乎得到了意想不到的结果。

You probably provide wrong end iterator to sort, as you can see last two entries from your input are the same as in output - sort simply does not include them in sorting.您可能提供了错误的end迭代器进行排序,因为您可以看到输入中的最后两个条目与输出中的相同 - sort 只是不将它们包含在排序中。

std::sort will sort pairs, first by first element - and if both are equal it will compare second. std::sort将对对std::sort排序,首先按第一个元素 - 如果两者相等,则将比较第二个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM