LeetCode刷题小结之vector的使用

Vector

1.特点:vector是C++标准模板库中的内容,它具有可变长度、可存取任意数据类型的特点,使用vector可以构建类似多维数组的数据结构。

2.常用方法:

#include 
#include 
#include 
using namespace std;
int main()
{
	vector test;

	test.push_back(8);
	test.push_back(5);
	test.push_back(3);
	test.push_back(7); //尾部加入元素

        reverse(test.begin(), test.end()); //反转vector

       for (vector::iterator it = test.begin(); it != test.end(); ++it)
		cout << *it << endl;  //使用迭代器遍历

	for (int i = 0; i < test.size(); ++i)
		cout << test[i] << endl; //使用索引遍历

	cout << test.size() << endl;  //返回v的长度

	test.pop_back(); //删除v最后一个元素,类似于弹栈,因此可用来实现栈

	cout << test.back() << endl; //取最后一个元素

	vector::iterator it = test.begin(); //声明迭代器

	it = test.erase(it); //删除迭代器it指向的元素,返回此迭代器的下一个迭代器

	sort(test.begin(), test.end()); //使元素由大到小排序,sort位于头文件algorithm

	test.resize(2);  //修改vector大小

	test.insert(it, -1); //在迭代器位置插入元素
	vector another (3,2); //声明vector, 值为 2 2 2 
	test.insert(test.begin(), another.begin(), another.end()); //vector中插入vector
	int list[] = { 0, 1, 2, 3 };
	test.insert(test.begin(), list, list + 3); //vector中插入数组

	find(test.begin(), test.end(), 3); //在vector中查找元素3是否存在,若存在返回指定迭代器;不存在返回test.end()

	test.clear(); //清空test中元素

	test.empty(); //test是否为空
}

3.自定义类型使用vector:

#include 
#include 
#include 
#include 
using namespace std;
struct Student {
	int id;
	string name;
	Student (int _id, string _name):id(_id), name(_name){}
	Student ():id(0), name(""){}
};
bool cmpAsc(const Student& s1, const Student& s2){
	return s1.id < s2.id;
}
bool cmpDes(const Student& s1, const Student& s2) {
	return s1.id > s2.id;
}
int main()
{
	vector myClass;
	myClass.push_back(Student(3131, "xiaoming"));
	myClass.push_back(Student(3212, "xiaoli"));
	myClass.push_back(Student(0312, "daming"));

	//其他用法与基本数据类型类似
	//对于自定义排序,需要重定义小于号(也可以在Sudent中重载小于号)
	sort(myClass.begin(), myClass.end(), cmpAsc); //由大到小排序
	sort(myClass.begin(), myClass.end(), cmpDes); //由小到大排序

	vector s(10); //使用这种声明语句时,在以下两种情况可以,否则会报错。
			       //1.在结构体中声明了默认构造函数(即无参构造函数)
			       //2.结构体中无构造函数,此时编译器会自动声明默认构造函数
}


参考:C++ vector



你可能感兴趣的:(LeetCode刷题)