0

我想使用 C++ 算法库中的 sort() 函数根据其第一列对 (nx2) 数组进行排序。我无法弄清楚在 sort() 函数中使用关于自定义函数的第三个参数的方法。下面的代码没有编译。

#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’
4

1 回答 1

0

此代码至少通过 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;
}
于 2013-10-20T14:18:07.463 回答