我刚开始学习C++,我想知道是否有一种方法可以按每个数组中的第二个值对二维数组进行排序。我还没有在网上找到任何方法,所以我在这里询问。
例如,您可以从以下位置开始:
int exampleArray[5][2] = {
{4, 20},
{1, 4},
{7, 15},
{8, 8},
{8, 1}
};在排序之后,数组将是
int exampleArray[5][2] = {
{8, 1},
{1, 4},
{8, 8},
{7, 15},
{4, 20}
};在Python语言中,您可以使用exampleArray.sort(key = lambda element : element[1])对其进行排序,但我不知道如何使用C++对其进行排序
发布于 2021-09-03 01:09:10
简短的答案是:不要那样做。C++从C继承了它的内置数组,它并不能很好地适应你想要做的事情。
合理相似且易于实现的方法是使用std::vector而不是数组。
std::vector<std::vector<int>> someVector {
{4, 20},
{1, 4},
{7, 15},
{8, 8},
{8, 1}
};根据每行中的第二项对其进行排序非常简单:
std::sort(someVector.begin(), someVector.end(),
[](auto const &a, auto const &b) { return a[1] < b[1]; });然后我们可以打印出结果来验证它是否如预期的那样工作:
for (auto const &row : someVector)
std::cout << row[0] << "\t" << row[1] << "\n";正如您所期望的,这会产生:
8 1
1 4
8 8
7 15
4 20发布于 2021-09-03 01:31:18
您可以使用结构来保存您的数据:
struct Data
{
int x,y;
};
vector<Data> a;使用std::sort,您可以使用lambda函数来实现您的目标
std::sort(a.begin(),a.end(),[](Data e1,Data e2){return e1.y<e2.y;});
发布于 2021-09-03 01:38:21
使用向量要简单得多,但是假设您不能使用std::vector,这里有一种基于answer given here的“排序”的替代方法
#include <iostream>
#include <algorithm>
int main()
{
int exampleArray[5][2] = {
{4, 20},
{1, 4},
{7, 15},
{8, 8},
{8, 1}
};
// create the indexing (there are 5 2D entries)
int index[] = {0,1,2,3,4};
// sort the index based on the second value in the 2D array
std::sort(index, index + 5, [&](int n1, int n2)
{ return exampleArray[n1][1] < exampleArray[n2][1]; });
// output results
for (int i = 0; i < 5; ++i)
std::cout << exampleArray[index[i]][0] << " " << exampleArray[index[i]][1] << "\n";
}输出:
8 1
1 4
8 8
7 15
4 20基本上,您希望根据2D数组中的第二个值对索引数组进行排序。这就是lambda函数所说的--索引数组被“排序”,而不是原始的2D数组。
排序完成后,使用索引数组以排序的方式访问2D数组中的项。
在此基础上,如果希望将更改存储在实际的2D数组中,则可以使用排序后的索引重新构建原始数组:
// rebuild the original array using the sorted index
int tempArray[5][2] = {};
for (int i = 0; i < 5; ++i)
{
tempArray[i][0] = exampleArray[index[i]][0];
tempArray[i][1] = exampleArray[index[i]][1];
}
// copy the new sorted array to the original array
memcpy(exampleArray, tempArray, sizeof(exampleArray));https://stackoverflow.com/questions/69038256
复制相似问题