在C ++ STL中,二维向量是向量的向量。
声明2D向量的语法:
vector<vector<T>> vector_name{ {elements}, {elements}, ...};
1)使用C ++ STL代码声明和打印2D向量(具有相同数量的元素)
//使用C ++ STL代码声明和打印2D矢量 #include <iostream> #include <vector> //对于矢量 using namespace std; int main(){ //初始化2D向量“ v1”"v1" with //相同数量的矢量元素 vector<vector<int> > v1{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; //打印2D向量的元素 for (int i = 0; i < v1.size(); i++) { for (int j = 0; j < v1[i].size(); j++) cout << v1[i][j] << " "; cout << endl; } return 0; }
输出结果
1 2 3 4 5 6 7 8 9
2)C ++ STL代码来声明和打印2D向量(具有不同数量的元素)
//使用C ++ STL代码声明和打印2D矢量 #include <iostream> #include <vector> //对于矢量 using namespace std; int main(){ //初始化2D向量“ v1”"v1" with //不同数量的矢量元素 vector<vector<int> > v1{ { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8, 9 } }; //打印2D向量的元素 for (int i = 0; i < v1.size(); i++) { for (int j = 0; j < v1[i].size(); j++) cout << v1[i][j] << " "; cout << endl; } return 0; }
输出结果
1 2 3 4 5 6 7 8 9
3)使用C ++ STL代码声明和打印2D向量(用户输入的行数,列数和元素数)
//使用C ++ STL代码声明和打印2D矢量 #include <iostream> #include <vector> //对于矢量 using namespace std; int main(){ int row; int col; // Input rows & columns cout << "Enter number of rows: "; cin >> row; cout << "Enter number of columns: "; cin >> col; //声明2D向量“ v1”"v1" with //给定的行数和列数 //并用0初始化 vector<vector<int> > v1(row, vector<int>(col, 0)); //输入向量的元素 for (int i = 0; i < v1.size(); i++) { for (int j = 0; j < v1[i].size(); j++) { cout << "Enter element: "; cin >> v1[i][j]; } } //打印2D向量的元素 cout << "2D vector elements..." << endl; for (int i = 0; i < v1.size(); i++) { for (int j = 0; j < v1[i].size(); j++) cout << v1[i][j] << " "; cout << endl; } return 0; }
输出结果
Enter number of rows: 3 Enter number of columns: 4 Enter element: 1 Enter element: 2 Enter element: 3 Enter element: 4 Enter element: 5 Enter element: 6 Enter element: 7 Enter element: 8 Enter element: 9 Enter element: 10 Enter element: 11 Enter element: 12 2D vector elements... 1 2 3 4 5 6 7 8 9 10 11 12