c ++向量库
Also referred to as vector of vectors, 2D vectors in C++ form the basis of creating matrices, tables, or any other structures, dynamically. Before arriving on the topic of 2D vectors in C++, it is advised to go through the tutorial of using single-dimensional vectors in C++.
也称为向量的向量,C ++中的2D向量构成动态创建矩阵,表或任何其他结构的基础。 在讨论C ++中的2D矢量主题之前,建议先阅读在C ++中使用一维矢量的教程。
包括Vector头文件 (Including the Vector header file)
It would be impossible for us to use vectors in C++, if not for the header files that are included at the beginning of the program. To make use of 2D vectors, we include:
如果没有C ++中的头文件,对于我们来说就不可能使用C ++中的向量。 为了利用2D向量,我们包括:
#include<vector>
Instead of including numerous kinds of Standard Template Libraries (STL) one by one, we can include all of them by:
与其一一包括许多种标准模板库(STL),我们不如通过以下方式将它们全部包括在内:
#include<bits/stdc++.h>
在C ++中初始化2D向量 (Initializing 2D vectors in C++)
Firstly, we will learn certain ways of initializing a 2-D vector. The following code snippet explains the initialization of a 2-D vector when all the elements are already known.
首先,我们将学习初始化二维矢量的某些方法。 以下代码段说明了所有元素都已知时的二维矢量初始化。
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<vector<int>> v {
{1, 0, 1}, {0, 1}, {1, 0, 1}};
for(int i=0;i<v.size();i++){
for(int j=0;j<v[i].size();j++)
cout<<v[i][j]<<" ";
cout<<endl;
}
}
After running the above code, we get the following output:
运行上面的代码后,我们得到以下输出:
1 0 1
0 1
1 0 1
The use of 'vector<vector<>>'
symbolizes that we are working on a vector of vectors. Each value inside the first set of braces, like '{1, 0, 1}'
and '{0, 1}'
are vectors independently.
'vector<vector<>>'
表示我们正在研究矢量的向量。 第一组大括号内的每个值(例如'{1, 0, 1}'
1,0,1 '{1, 0, 1}'
和'{0, 1}'
都是独立的向量。