Sort 2 dimensional c array with std::sort

前端 未结 2 443
南笙
南笙 2021-01-15 17:13

I cannot seem to sort a 2 dimensional c array with std::sort. I can however sort a one dimensional array. This is in a case where I am being handed a c array in a c++ progra

2条回答
  •  情深已故
    2021-01-15 17:42

    Maybe there is some way to turn it into a std::array without copying it?

    Perhaps not turning into a std::array per se, but an alternative approach might be to cast the 2D C-style arrays into a std::array reference just for the sorting. Doing so in reliance on the standard saying an std::array representation in memory at least begins with its C-style array equivalent. See here under [array.overview§2]:

    An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T.

    In practice, the following usage of reinterpret_cast is most probably safe, but do note that unless there is a special exception for it somewhere in the standard, it would formally be undefined behaviour:

    #include 
    #include 
    #include 
    
    int main() {
      auto two_dim_less = [](std::array& a, std::array& b) {
          return a[1] < b[1]; };
    
      int two_dim[][2] = {{1, 8}, {2, 4}, {3, 10}, {4, 40}, {5, 1}};
    
      std::array, 5>& arr =
        *reinterpret_cast, 5>*>(&two_dim);
    
      std::sort(arr.begin(), arr.end(), two_dim_less);
    
      for (int i = 0; i < 5; i++)
        std::cout << two_dim[i][0] << ", " << two_dim[i][1] << '\n';
    
      return 0;
    }
    

    Output:

    5, 1
    2, 4
    1, 8
    3, 10
    4, 40
    

    Regarding the use of std::qsort(), note that it is potentially slower than std::sort() due to the latter allowing to inline the comparisons while the former doesn't.

提交回复
热议问题