排序C ++中的二维数组使用内置的函数(或任何其他方法)? [英] Sort a 2D array in C++ using built in functions(or any other method)?

查看:217
本文介绍了排序C ++中的二维数组使用内置的函数(或任何其他方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组如下图所示。 (数组[5] [2]

I have a 2D array like below. ( array[5][2] )

20 11

10 20

39 14

29 15

22 23

排序后应该像下面。

10 20

20 11

22 23

29 15

39 14

这意味着数组应该进行排序只比较第一价值观明杆

that means the array should be sorted comparing the first coloum values only.

在Java中有一个内置的功能能力做到这一点。像下面。

In Java there is a built in function capability to do that. like below.

Arrays.sort(a, new Comparator<Long[]>() {

            @Override
            public int compare(Long[] o1, Long[] o2) {

                Long t1 = o1[1];
                Long p1 = o1[0];
                Long t2 = o2[1];
                Long p2 = o2[0];

                if (t1 == t2) {
                    return (p1 > p2 ? 1 : (p1 == p2 ? 0 : -1));
                } else {
                    return (t1 < t2 ? -1 : 1);
                }

            }
        });

那么,有没有C ++内置功能的能力做这几样东西或我怎么能做到这一点的C ++(最快的实现)?

So is there any C++ built in function capability to do these kind of stuff or how can i do this in C++ (the fastest implementation) ?

在此先感谢:)

推荐答案

C和C ++的内置阵列是非常不灵活,除其他事项外,他们不能进行分配。

The built-in arrays of C and C++ are very inflexible, among other things they cannot be assigned.

您最好的办法是从C ++标准库中的数组类,至少在内部尺寸:

Your best option would be the 'array' class from the C++ standard library, at least for the inner dimension:

array<int, 2> a[5] = { { 20, 11 },
{ 10, 20 },
{ 39, 14 },
{ 29, 15 },
{ 22, 23 } };

sort( a, a + 5 );

编辑:一些更多的解释

在这里我们使用的std该财产::阵'&LT;'默认情况下,他们按字母顺序比较,即开始与第一个元素。为了不同的事情排序,我们要拿出一个比较对象,所以如果你想使用第二列作为排序关键字,你不得不这样做:

Some more explanations.

Here we use the property of std::array that '<' by default compares them lexicographically, i.e. starts with the first element. In order to sort things differently we have to come up with an comparator object, so if you want to use the second column as sort key you have to do this:

auto comp = []( const array<int, 2>& u, const array<int, 2>& v )
      { return u[1] < v[1]; };
sort( a, a + 5, comp );

和在第一则留言中提到,排序(A,A + 5 ... 只是为了清洁一个丑陋的缩写形式排序(性病::开始(一)的std ::结束(一)...

And as mentioned in the first comment, sort(a, a+5 ... is just an ugly short form for the cleaner sort(std::begin(a), std::end(a) ...

这篇关于排序C ++中的二维数组使用内置的函数(或任何其他方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆