stl向量
C ++ STL中的2D矢量 (2D Vector in C++ STL)
In C++ STL, a 2D vector is a vector of vector.
在C ++ STL中,二维向量是向量的向量。
Syntax to declare a 2D vector:
声明2D向量的语法:
vector<vector<T>> vector_name{ {elements}, {elements}, ...};
1) C++ STL code to declare and print a 2D Vector (with same number of elements)
1)使用C ++ STL代码声明和打印2D向量(具有相同数量的元素)
// C++ STL code to declare and print a 2D Vector
#include <iostream>
#include <vector> // for vectors
using namespace std;
int main()
{
// Initializing 2D vector "v1" with
// same number of vector elements
vector<vector<int> > v1{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// Printing the 2D vector's elements
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;
}
Output
输出量
1 2 3
4 5 6
7 8 9
2) C++ STL code to declare and print a 2D Vector (with different number of elements)
2)使用C ++ STL代码声明和打印2D向量(具有不同数量的元素)
// C++ STL code to declare and print a 2D Vector
#include <iostream>
#include <vector> // for vectors
using namespace std;
int main()
{
// Initializing 2D vector "v1" with
// different number of vector elements
vector<vector<int> > v1{ { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8, 9 } };
// Printing the 2D vector's elements
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;
}
Output
输出量
1 2 3
4 5
6 7 8 9
3) C++ STL code to declare and print a 2D Vector (Numbers of rows, columns and elements input by the user)
3)使用C ++ STL代码声明和打印2D向量(用户输入的行数,列数和元素数)
// C++ STL code to declare and print a 2D Vector
#include <iostream>
#include <vector> // for vectors
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;
// Declaring 2D vector "v1" with
// given number of rows and columns
// and initialized with 0
vector<vector<int> > v1(row, vector<int>(col, 0));
// Input vector's elements
for (int i = 0; i < v1.size(); i++) {
for (int j = 0; j < v1[i].size(); j++) {
cout << "Enter element: ";
cin >> v1[i][j];
}
}
// Printing the 2D vector's elements
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;
}
Output
输出量
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
翻译自: https://www.includehelp.com/stl/2d-vector-in-cpp-stl-with-user-defined-size.aspx
stl向量