Сортировка 2D-вектора в C ++ | Набор 3 (по количеству столбцов)
Мы обсудили некоторые случаи сортировки 2D-вектора в наборах 1 и 2 ниже.
Сортировка 2D-вектора в C ++ | Набор 1 (по строке и столбцу)
Сортировка 2D-вектора в C ++ | Набор 2 (в порядке убывания по строке и столбцу)
Другие случаи обсуждаются в этой статье
Как упоминалось в одной из статей, опубликованных в этом наборе, 2D-вектор также может иметь строки с разным количеством столбцов. Это свойство отличается от 2D-массива, в котором все строки имеют одинаковое количество столбцов.
// C++ code to demonstrate 2D Vector // with different no. of columns #include<iostream> #include<vector> // for 2D vector using namespace std; int main() { // Initializing 2D vector "vect" with // values vector< vector< int > > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector for ( int i=0; i<vect.size(); i++) { //loop till the size of particular //row for ( int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " " ; cout << endl; } return 0; } |
Выход:
1 2 3 4 5 6
Случай 5: Сортировка 2D-вектора по номеру столбцов в строке в порядке возрастания.
В этом типе сортировки 2D-вектор сортируется по номеру. столбца в порядке возрастания. Это достигается передачей третьего аргумента в «sort ()» в качестве вызова явной функции, определенной пользователем.
// C++ code to demonstrate sorting of // 2D vector on basis of no. of columns // in ascending order #include<iostream> #include<vector> // for 2D vector #include<algorithm> // for sort() using namespace std; // Driver function to sort the 2D vector // on basis of a no. of columns in // ascending order bool sizecom( const vector< int >& v1, const vector< int >& v2) { return v1.size() < v2.size(); } int main() { // Initializing 2D vector "vect" with // values vector< vector< int > > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector before sorting cout << "The Matrix before sorting is:
" ; for ( int i=0; i<vect.size(); i++) { //loop till the size of particular //row for ( int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " " ; cout << endl; } //Use of "sort()" for sorting on //basis of no. of columns in //ascending order. sort(vect.begin(), vect.end(), sizecom); // Displaying the 2D vector after sorting cout << "The Matrix after sorting is:
" ; for ( int i=0; i<vect.size(); i++) { //loop till the size of particular //row for ( int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " " ; cout << endl; } return 0; } |
Выход:
Матрица перед сортировкой: 1 2 3 4 5 6 Матрица после сортировки: 6 1 2 3 4 5
Случай 6: Сортировка 2D-вектора по номеру столбцов в строке в порядке убывания.
В этом типе сортировки 2D-вектор сортируется по номеру. столбца в порядке убывания. Это достигается передачей третьего аргумента в «sort ()» в качестве вызова явной функции, определенной пользователем.
// C++ code to demonstrate sorting of // 2D vector on basis of no. of columns // in descending order #include<iostream> #include<vector> // for 2D vector #include<algorithm> // for sort() using namespace std; // Driver function to sort the 2D vector // on basis of a no. of columns in // descending order bool sizecom( const vector< int >& v1, const vector< int >& v2) { return v1.size() > v2.size(); } int main() { // Initializing 2D vector "vect" with // values vector< vector< int > > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector before sorting cout << "The Matrix before sorting is:
" ; for ( int i=0; i<vect.size(); i++) { //loop till the size of particular //row for ( int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " " ; cout << endl; } //Use of "sort()" for sorting on //basis of no. of columns in //descending order. sort(vect.begin(), vect.end(), sizecom); // Displaying the 2D vector after sorting cout << "The Matrix after sorting is:
" ; for ( int i=0; i<vect.size(); i++) { //loop till the size of particular //row for ( int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " " ; cout << endl; } return 0; } |
Выход:
Матрица перед сортировкой: 1 2 3 4 5 6 Матрица после сортировки: 3 4 5 1 2 6
Автором этой статьи является Манджит Сингх. Если вам нравится GeeksforGeeks и вы хотите внести свой вклад, вы также можете написать статью с помощью метода влиятельности. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.