我想使用 C++ 年算法库中的 sort( ) 函数根据其第一列对 (nx2) 数组进行排序。我无法弄清楚在 sort() 函数中使用有关自定义函数的第 3 个参数的方法。下面的代码未编译。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,k,i,j,missile[100000][2];
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%d %d",&missile[i][0], &missile[i][1]);
}
bool sortFunc( int *missile[i][0], int *missile[j][0])
{
return missile[i][0]<missile[j][0];
}
sort(missile,missile+n,sortFunc);
for (int i = 0; i < n; ++i)
{
printf("%d %dn",missile[i][0],missile[i][1]);
}
return 0;
}
根据我所理解的内容,我将代码更改为
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
scanf("%d",&n);
vector< pair<int,int> > missile(n);
for(auto p:missile)
scanf("%d %d",&(p.first),&(p.second));
sort(begin(missile),end(missile),less) //Using the default comparator for pair
for(auto p:missile)
printf("%d %dn",p.first,p.second);
return 0;
}
仍然收到许多编译错误
hackerrank_missile.cpp: In function ‘int main()’:
hackerrank_missile.cpp:12: error: a function-definition is not allowed here before ‘:’ token
hackerrank_missile.cpp:15: error: ‘begin’ was not declared in this scope
hackerrank_missile.cpp:15: error: ‘end’ was not declared in this scope
hackerrank_missile.cpp:15: error: missing template arguments before ‘)’ token
hackerrank_missile.cpp:17: error: expected `;' before ‘for’
hackerrank_missile.cpp:17: error: expected primary-expression before ‘for’
hackerrank_missile.cpp:17: error: expected `)' before ‘for’
hackerrank_missile.cpp:17: error: a function-definition is not allowed here before ‘:’ token
hackerrank_missile.cpp:19: error: expected primary-expression before ‘return’
hackerrank_missile.cpp:19: error: expected `;' before ‘return’
hackerrank_missile.cpp:19: error: expected primary-expression before ‘return’
hackerrank_missile.cpp:19: error: expected `)' before ‘return’
这段代码至少通过编译(使用 c++11,C 样式 IO 除外)通过 clang++ test.cc -std=c++11 -stdlib=libc++ -Weverything -Wno-c++98-compat
.如果它能如你所愿,我不知道。
#include <cstdio>
#include <vector>
#include <algorithm>
int main() {
std::size_t n;
std::scanf("%ld",&n);
std::vector<std::pair<int,int>> missile(n);
for(auto&p:missile)
std::scanf("%d %d",&(p.first),&(p.second));
std::sort(std::begin(missile),std::end(missile),[](std::pair<int,int> const&i,
std::pair<int,int> const&j)
{ return i.first < j.first; });
for(auto p:missile)
std::printf("%d %dn",p.first,p.second);
return 0;
}