Dynamic growth of array space

When writing code, you often encounter the situation of uncertain array space. If you use an array definition in advance, you need to allocate enough space to prevent it from being insufficient, which is likely to cause a waste of space. Therefore, using vector to store arrays can be divided into two situations:
1. The number of arrays is in the form of input:

#include<bits\stdc++.h>
using namespace std;

int main() {
    
    
	int n; cin >> n;//输入数组的个数
	//vector的初始化的参数还可以是:同类型向量或数组,若采用这两种参数,那么缺省的第二个参数为向量或数组尾地址
	vector<string> arr(n);
	for (int i = 0; i < n; i++) {
    
    
		cin >> arr[i];
		arr[i] += ",第" + to_string(i+1) + "次";//字符拼接
	}
	for (int i = 0; i < n; i++)
		cout << arr[i] << endl;
	system("pause");
	return 0;
}

operation result:
Insert picture description here

2. The number of arrays increases with the number of branches:

#include<bits\stdc++.h>
using namespace std;

int main() {
    
    
	vector<string> arr; //不写参数时,长度默认为0,即等价于vector<string> arr(0); 
	int n = 10;
	for (int i = 0; i < n; i++) {
    
    
		//单数增加,也可以是其他条件
		if (i % 2 == 1) {
    
    
		    //或者用push_back()插入到末端
			arr.resize(arr.size() + 1); //容量+1
			cin >> arr[arr.size() - 1]; //输入
			arr[arr.size() - 1] += ",第" + to_string(arr.size()) + "次"; //字符拼接
		}
	}
	for (int i = 0; i < arr.size(); i++)
		cout << arr[i] << endl;

	system("pause");
	return 0;
}

operation result:

Guess you like

Origin blog.csdn.net/weixin_42419611/article/details/104924954