C++ Vector 使用详解

Vector

下面是vector的基础使用方法。

#include 
#include 
using namespace std;


int main(){
	vector vec;
	vec.push_back(1);
	vec.push_back(2);
	vec.push_back(3);
	for (int i = 0; i < vec.size(); i++){
		cout << vec[i] << endl;
	}
	// 清空vec内数据 
	vec.clear();
	for (int i = 0; i < vec.size(); i++){
		cout << vec[i] << endl;
	}
	// 清除vec的内存 
	vector().swap(vec);
	return 0;
} 

同样结构体也是可以的

#include 
#include 
using namespace std;


struct Student{
	string name;
	int age;
}; 

int main(){
	vectorv;
	Student stu1, stu2;
	stu1.name = "玛卡巴卡";
	stu1.age = 10;
	stu2.name = "胖橙";
	stu2.age = 20;
	v.push_back(stu1);
	v.push_back(stu2);
	for (int i = 0; i < v.size(); i++){
		cout << v[i].name << " " << v[i].age << endl;
	}
	return 0;
} 

下面是快速初始化,构造的方式,vectorv中的第一个参数是长度大小。第二个参数是初始值。

#include 
#include 
using namespace std;

int main(){
	int n;
	cin >> n;
	vectorv(n, 0);

	for (int i = 0; i < v.size(); i++){
		cout << v[i] << endl;
	}
	return 0;
} 

二维的解决方法:

int n = 5;
vector > vec2;
for (int i = 0; i < vec2.size(); i++){
	vector x(i + 1, 1);
	vec2.push_back(x);
}

二维的初始化

int main(){
	int n = 10, m = 5;
	vector > vec(n, vector(m, 0));
	for (int i  = 0; i < n; i++){
		for (int j = 0; j < m; j++){
			cout << vec[i][j] << " ";
		}
		cout << endl; 
	}
	return 0;
} 

你可能感兴趣的:(算法,c++,算法,贪心算法)