我正在尝试按照第一个元素对c++子数组进行排序。我的代码目前设置如下:
int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}};
int n = sizeof(umbrellas) / sizeof(umbrellas[0]);
sort(umbrellas, umbrellas + n, greater<int>());排序函数似乎不能正常工作,当我运行代码时,它会生成错误。是否有办法对数组进行排序
{{5, 6}, {2, 7}, {9, 20}}转到
{{2, 7}, {5, 6}, {9, 20}}发布于 2022-07-02 08:52:13
使用std::vector of std::vector作为您的容器,这样排序就容易多了。std::vector不仅是C++的首选容器,而且在其上使用STL函数是非常简单和直接的,没有任何可证实的开销。
将数据定义为
std::vector<std::vector<int>> umbrellas{
{5, 6},
{2, 7},
{9, 20}
};现在,您可以使用自定义比较器lambda,它接受两个向量元素引用,并在上述向量的第一个元素小于下面的元素时返回True。
std::sort(umbrellas.begin(),
umbrellas.end(),
[](const std::vector<int> &above, const std::vector<int> &below)
{
return (above[0] < below[0]);
});以及产出:
for (auto &&row : umbrellas) {
for (auto element : row) {
std::cout<< element<< " ";
}
std::cout<< "\n";
}2 7
5 6
9 20把这个带到C++20上就更容易了:
std::ranges::sort(umbrellas, std::less(),
[](const auto &v) { return v[0];});发布于 2022-07-02 00:58:39
如果时间复杂度不重要,则该代码将实现O(n^2)复杂度所需的目标。
int arr[3][2] = {{5, 6}, {2, 7}, {9, 20}};
int n = sizeof(arr) / sizeof(arr[0]);
for(int i = 0 ; i < n - 1; i++){
for(int j = 0 ; j < n - 1 ; j++){
if(arr[j][0] > arr[j + 1][0])
swap(arr[j],arr[j + 1]);
}
}https://stackoverflow.com/questions/72835703
复制相似问题