C++ C++;:基于一行的二维数组排序
我有一个2行的2D数组,其中有非常大的数字(最多10^9)。 我正在尝试根据第0行对数组进行排序 例如:我有一个数组:C++ C++;:基于一行的二维数组排序,c++,arrays,sorting,C++,Arrays,Sorting,我有一个2行的2D数组,其中有非常大的数字(最多10^9)。 我正在尝试根据第0行对数组进行排序 例如:我有一个数组:A[5][2]={{1,0},{3,1},{2,2},{6,3},{5,4},其中第二行是元素的索引 现在我想对数组进行排序,保留原始索引 排序后,A应为: A[5][2]={{1,0},{2,2},{3,1},{5,4},{6,3}} 我做了以下工作: long long a[n+1][2]; for (long long i = 0; i < n; i++
A[5][2]={{1,0},{3,1},{2,2},{6,3},{5,4}
,其中第二行是元素的索引
现在我想对数组进行排序,保留原始索引
排序后,A应为:
A[5][2]={{1,0},{2,2},{3,1},{5,4},{6,3}}
我做了以下工作:
long long a[n+1][2];
for (long long i = 0; i < n; i++)
{
cin>>a[i][0];
a[i][1]=i;
}
qsort(a, n, sizeof a[0], compare);
它适用于较小的数值。对于较大的值,我得到运行时错误(SIGSEGV)
有人能帮忙改正错误吗?还是有更有效的方法
注意:我在比较函数中尝试了很长时间,但它给出了转换错误。错误:从'll(*)(const void*,const void*){aka long long int(*)(const void*,const void*)}'到'u compare\u fn\u t{aka int(*)(const void*,const void*)}'[-fppermissive]的转换无效。
编辑:实际上,我可以在排序后只处理索引。首先,数组声明不正确(下面的示例代码显示了正确的声明) 第二,我建议不使用第一行,只对第二行索引进行排序。由于第二行用作索引器,因此无需对第一行进行排序 < P >第三,不推荐使用C++中的<代码> qStase。
qsort
不是类型安全的。您必须将void
指针强制转换为使用qsort
排序的类型。如果转换操作不正确,则程序存在运行时问题qsort
不能用于非POD类型(任何与C
不兼容的类型)李>
std::sort
非常易于使用#include <algorithm>
#include <iostream>
int main()
{
int A[2][5] = { {1,3,2,6,5},{0,1,2,3,4} };
// sort the index row, not the "data" row
std::sort(A[1], A[1] + 5,
[&](int n1, int n2){ return A[0][n1] < A[0][n2]; });
// output results
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 5; ++j)
{
if (i == 0) // if this is a data row
std::cout << A[i][A[1][j]] << " ";
else // this is an index row
std::cout << A[i][j] << " ";
}
std::cout << "\n";
}
}
#包括
std::sort
在第二行而不是第一行工作。然后比较lambda根据第一行中的数据对第二行进行排序
输出循环显示了在给定第二行的情况下如何索引第一行。例如,要获取第一行中已排序的第三个数字:
A[0][A[1][2]
由于A[1][2]
是第三个排序数的索引,因此第三个排序数是A[0][A[1][2]
编辑:
如果您试图使用动态二维数组,那么请使用std::vector
,因为我不知道它的用途,所以我可能是错的,但也许您应该使用带有两个字段的结构或类:index和number、重载=运算符和使用对象数组,并且只使用排序方法 可能是因为您混合了long-long
和int
?最好将这个问题标记为C,因为您使用了大量C,而没有C++@Buckster为什么std::sort
不兼容?也许你不知道如何正确使用它。@Buckster无论qsort
能做什么,std::sort
都能做,而且做得更好。你把这个问题标注为<代码> C++ >代码>,不推荐使用C++中的代码> qStase。可能的副本:我尝试了用户驱动的输入。比较函数上存在编译错误。long int a[2][n+1]代码>这是无效的C++。不能使用变量定义数组的大小。您给出的是 STD::排序< /COD>不是真实C++的东西,这就是为什么错误提到“N3639”。C++中的动态数组是使用<代码> STD::vector < /代码>。@ Buckster请参见我的编辑和使用向量的链接到代码。
#include <algorithm>
#include <iostream>
int main()
{
int A[2][5] = { {1,3,2,6,5},{0,1,2,3,4} };
// sort the index row, not the "data" row
std::sort(A[1], A[1] + 5,
[&](int n1, int n2){ return A[0][n1] < A[0][n2]; });
// output results
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 5; ++j)
{
if (i == 0) // if this is a data row
std::cout << A[i][A[1][j]] << " ";
else // this is an index row
std::cout << A[i][j] << " ";
}
std::cout << "\n";
}
}