假设我有一个大小为n的方阵A,定义为std::vector。
std::vector<double> A(n*n);
矩阵的元素可以按常规方式访问:
double a_ij = A[i*n + j];
我需要按矩阵的第一列进行升序排序。
使用qsort函数和函数指针可以对数组进行操作,但我希望找到一种使用向量和 std::sort
完成此操作的方法。
另外,请注意我不想将矩阵定义为向量的向量,因为考虑性能原因。
编辑:
我传递给 qsort 的函数:
static int comparisonFunction(const void* firstRow, const void* secondRow)
{
if (((double *)firstRow)[0] < ((double *)secondRow)[0]) return -1;
else if (((double *)secondRow)[0] < ((double *)firstRow)[0]) return 1;
return 0;
}
还有这个调用:
std::qsort(matrixArray, nbRows, sizeof(double)*nbRows, comparisonFunction);
begin
和end
迭代行。 - bolov