排序2D C++子阵列中的第一个元素数组
我正在尝试按第一个元素对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}}
数组进行分类?
I am trying to sort a c++ subarray by first element.
My code is currently set up like this:
int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}};
int n = sizeof(umbrellas) / sizeof(umbrellas[0]);
sort(umbrellas, umbrellas + n, greater<int>());
The sort function doesn't seem to be functioning properly and when I run the code it generates errors. Is there a way to sort the array from
{{5, 6}, {2, 7}, {9, 20}}
into
{{2, 7}, {5, 6}, {9, 20}}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
std :: vector
std :: vector
当您的容器和排序变得更加容易使用时。不仅std :: vector
C ++的首选容器,而且在其上使用STL功能更简单,直接,而没有任何实质性的开销。现在定义数据,
您可以使用自定义比较器lambda,该lambda列入两个向量元素引用,并在上述矢量的第一个元素小于下面的元素时返回true。
和输出:
将其带到C ++ 20,甚至更容易:
Use a
std::vector
ofstd::vector
as your container and the sort becomes much easier to do with. Not only isstd::vector
the preferred container for C++ but using STL functions on it is way simpler and direct , without any substantiable overhead.Define your data as
Now you can use a custom comparator lambda that takes in two vector element references and returns True when the first element of the above vector is smaller than that of the one below.
And the output :
Taking this to C++20 it's even easier:
如果时间复杂性无关紧要,则此代码将通过O(n^2)复杂性实现所需的时间
If time complexity doesn't matter, this code will achieve the desired with O(n^2) complexity