Simple use of vector<vector<int>> in C++

vector<vector<int> >In fact, it is a container nested container, the element type of the outer container is type, and the element type of vector<int>the inner container is inttype ;

1. Definition:

vector<vector<int> > A;	//正确的定义方式,后面的尖括号前要加上空格
vector<vector<int>> A;	//c++11之前这样定义是错误的,c++11之后支持这种定义方式

2. Length

//vector<vector<int> >A中的vector元素的个数
len = A.size();
//vector<vector<int> >A中第i个vector元素的长度
len = A[i].size();

3. Access an element

A[row][col\]: When accessing an element, the method is similar to a two-dimensional array

printf("%d\n", A[1][2]); 

2. Insert elements

Idea: Create a small container vector<int> b, assign a value to the small container, and then put the small container into the large container;

Case 1:

To defineA = [[0,1,2],[3,4,5]]

vector<vector<int> > A;  // 大容器
//A.push_back里必须是vector
vector<int> B;  // 小容器
B.push_back(0);
B.push_back(1);
B.push_back(2);
A.push_back(B); // 小容器放入大容器
B.clear();   // 小容器元素清空
B.push_back(3);
B.push_back(4);
B.push_back(5);
A.push_back(B);

Case 2: Keyboard input n-dimensional matrix, converted to two-dimensional vector

#include <iostream>
#include <vector>

using namespace std;
int main() {
    
    
	vector<vector<int> > v;
	vector<int> temp;

	int n ,i ,j,num;

	cout << "input the dimension:" ;
	cin >> n;
	cout << "请输入" << n << "*"<<n << "的矩阵"<<endl; 

	// 输入元素  
	for(i=0; i<n; i++) {
    
    
		temp.clear(); // 清空temp内元素; 
		for(j=0; j<n; j++) {
    
    
			cin >>  num;
			temp.push_back(num);
		}
		v.push_back(temp);
	}
	
	cout << "<----- 遍历输出所有元素 ----->"<<endl;
	for(i=0; i<n; i++) {
    
    
		for(j=0; j<n; j++) {
    
    
			cout<<v[i][j] << "  ";
		}
		cout <<endl;
	}
	
	return 0;
}

Operation
insert image description here


refer to:

https://blog.csdn.net/u013068755/article/details/70198924

https://www.cnblogs.com/tyty-Somnuspoppy/p/9361821.html

Guess you like

Origin blog.csdn.net/VariatioZbw/article/details/116485536