2016-01-22 93 views
-2

我需要根據特定列對C++中的矩陣進行排序,並且必須儘可能地提高性能。 這是被存儲在vector<vector> Rel[][4] 我需要對它進行排序爲DUEDATE矩陣矩陣分類C++

JobId;DueDate;RelDate;TardPenalty 
1;575;4;1 
2;563;70;2 
3;483;1;8 
4;519;68;1 
5;540;64;10 
6;546;126;8 
7;550;2;6 
8;563;70;4 
9;470;9;6 
10;480;21;3 
11;489;6;6 
12;593;29;10 
13;532;37;7 
14;591;25;10 
15;468;7;1 
16;570;26;1 
17;498;73;5 
18;504;0;4 
19;510;5;10 
20;541;15;8 
21;583;13;3 
22;532;37;3 
23;534;42;8 
24;585;16;4 
25;491;8;5 
26;584;66;9 
27;563;70;7 
28;555;40;3 
29;475;65;8 
30;549;27;6 

(REL [] [1])和跟蹤的其他數據。 有人可以幫我嗎?我嘗試了sort()函數,但對矩陣並不好。

非常感謝

編輯: 我做了一個矩陣快速排序算法,但它崩潰了,這裏是我的代碼

void quickSort(vector<vector<int>> arr, int left, int right) { 
    int i = left, j = right; 
    vector<int> tmp; 
    int pivot = arr[(left + right)/2][1]; 

    /* partition */ 
    while (i <= j) { 
     while (arr[i][1] < pivot) 
      i++; 
     while (arr[j][1] > pivot) 
      j--; 
     if (i <= j) { 
      for (int l = 0; l < 4; l++) { 
       tmp[l] = arr[i][l]; 
      } 
      for (int l = 0; l < 4; l++) { 
       arr[i][l] = arr[j][l]; 
      } 
      for (int l = 0; l < 4; l++) { 
       arr[j][l] = tmp[l]; 
      } 

      i++; 
      j--; 
     } 
    }; 

    /* recursion */ 
    if (left < j) 
     quickSort(arr, left, j); 
    if (i < right) 
     quickSort(arr, i, right); 
} 
+0

你有一個vwctors矢量陣列嗎?如果將矩陣存儲爲行的向量,那麼編寫'sort'的自定義比較並不困難。 – molbdnilo

+0

是的,這是一個向量的行,但我不知道如何編寫一個執行排序功能 – ScazzoMatto

+0

與'矢量'你已經扔出窗口的性能。使用[Eigen](http://eigen.tuxfamily.org/dox/GettingStarted.html)等。 – nwp

回答

2

這看起來並不像一個矩陣給我。這看起來像一系列記錄。我將定義一個記錄:

struct Record 
{ 
    int JobId; 
    int DueDate; 
    int RelDate; 
    int TardPenalt 
}; 

存儲中的數據作爲

std::vector<Record> Rel; 

定義一個比較函數:

bool sortByDate(const Record& lhs, const Record& rhs) 
{ 
    return lhs.DueDate < rhs.DueDate; 
} 

和排序使用標準功能:

std::sort(Rel.begin(), Rel.end(), sortByDate); 

如果你使用sortByDate內聯,你不太可能做得更好。