2015-05-19 61 views
3

我想对用户给出的行或列的2d数组进行排序。我有的代码可以按升序排序,但不能降序排列。使用sort()而不是升序C++

void sortArray(int arr[12][12], int index, int row) 
{ 
    if (row == 0) 
    { 
     sort(arr[index] , arr[index] + 12); 
    } 
    else 
    { 
     int tempArr[12]; 
     getColArr(arr, tempArr, index); 
     sort(tempArr, tempArr + 12); 
     for (int i = 0; i < 12; i++) 
     { 
      arr[i][0] = tempArr[i]; 
     } 
    } 
} 

如何将其更改为降序?

+0

见http://stackoverflow.com/questions/4008253/how-to-sort-c-array-in -asc和 - 递减模式 – Javia1492

回答

2

可以使用反向迭代rbegin来咬,例如:

int main() 
{ 
    int vec[6] {1,2,3,4,5,6}; 
    sort(rbegin(vec), rend(vec)); 

    for (const auto &i : vec) 
     cout << i << " "; 
} 

输出:6 5 4 3 2 1

或者你可以使用lambda作为第三个参数来排序:

int vec[6] = {1,2,3,4,5,6}; 
sort(vec, vec+6, [](int i, int j){return i>j;}); 

如果您没有支持C++ 11或C++ 14的编译器,则可以创建自己的比较函数并通过它作为第三个参数来排序:

bool isGreater(int i, int j) 
{ 
    return i > j; 
} 

int main() 
{ 
    int vec[6] = {1,2,3,4,5,6}; 
    sort(vec, vec+6, isGreater); 

    for (int i = 0; i != 6; ++i) 
     cout << vec[i] << " "; 
} 

输出:6 5 4 3 2 1

4

使用std::greater作为FYI..when使用std::sort没有第三个参数的std::sort

std::sort(begin(vec), end(vec),std::greater<int>()); 

第三参数,第三个参数默认为std::less

0

sort只能按升序排序...但您可以选择升序的方式。

如果你告诉sortxy是按升序排列,当且仅当x > y,然后排序顺序将是按照operator >升序排列,这是同样的事情,根据operator <降序排列。

你可以写自己的自定义函子来做到这一点或使用lambda,但标准库已经具备用于此目的的函子:

using std::sort; 
sort(begin(arr), end(arr), std::greater<int>()); 

在C++ 14,你应该使用std::greater<>代替std::greater<int>

1

使用 sort(arr [index],arr [index] + 12,std :: greater());

insted的的

sort(arr[index] , arr[index] + 12); 

对于升序排序;

//Sorts the elements in the range [first,last) into ascending order. 
std::sort(tempArr, tempArr + 12); // default sort 

对于降序排序,

//you can use the comparator, the third argument in sort() 
std::sort(tempArr, tempArr + 12, std::greater<int>()); 

更多的,请参阅http://www.cplusplus.com/reference/algorithm/sort/