我希望使用nx2中的算法库中的sort( )函数,根据其第一列对( C++ )数组进行排序。我无法找到使用第三个参数的方法,该参数涉及()函数中的自定义函数。下面的代码没有编译。
#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 %d\n",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 %d\n",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’发布于 2013-10-20 14:18:07
这段代码至少通过clang++ test.cc -std=c++11 -stdlib=libc++ -Weverything -Wno-c++98-compat编译(除了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 %d\n",p.first,p.second);
return 0;
}https://stackoverflow.com/questions/19478047
复制相似问题