给定数组向量,任务是对它们进行排序。
例子:
Input: [[1, 2, 3], [10, 20, 30], [30, 60, 90], [10, 20, 10]]
Output: [[1, 2, 3], [10, 20, 10], [10, 20, 30], [30, 60, 90]]
Input: [[7, 2, 9], [5, 20, 11], [6, 16, 19]]
Output: [[5, 20, 11], [6, 16, 19], [7, 2, 9]]
方法:
使用内置sort()对数组向量进行排序 在C++ STL中,它需要一个在boost库中定义的数组模板来存储数组向量。
std:: vector
where, std::array is a container that encapsulates fixed size arrays.
在此问题中,sort()函数采用两个参数first(向量的开始位置)和second(向量的结束位置)对数组的向量(具有随机访问权限的项)进行排序。下面是一个简单的程序,用于显示sort()的工作方式。
CPP
// C++ program to sort the vector
// of array by sort() function
// using STL in c++
#include
#include
#include
#include
using namespace std;
#define N 3
// Function to print vector of arrays
void print(vector > vect)
{
// Displaying the vector of arrays
// ranged for loop is supported
for (array i : vect) {
for (auto x : i)
cout << x << " ";
cout << endl;
}
}
// Driver code
int main()
{
// std::array is a container that
// encapsulates fixed size arrays.
vector > vect;
vect.push_back({ 1, 2, 3 });
vect.push_back({ 10, 20, 30 });
vect.push_back({ 30, 60, 90 });
vect.push_back({ 10, 20, 10 });
cout << "Vector of arrays"
<< " before sorting: \n";
print(vect);
// Sorting the vector using built-in sort()
// defined in algorithm header in C++ STL
sort(vect.begin(), vect.end());
cout << "Vector of arrays"
<< " after sorting: \n";
print(vect);
// End of program
return 0;
}
输出:
Vector of arrays before sorting:
1 2 3
10 20 30
30 60 90
10 20 10
Vector of arrays after sorting:
1 2 3
10 20 10
10 20 30
30 60 90
想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。