C++的vector的简单使用

本文为学习C++的阅读、学习笔记,如有错漏请联系作者。

1. 基本概念

    vector是一个类模板,在C++中使用模板可以编写一个类定义或函数定义,而用于多种不同的数据类型。vector是同一种类型的对象的集合,由于可以包含其他对象的特性,所以也将vector称为容器。

2. 使用方法

    要使用vector类模板,需要添加头文件,并使用using声明:

#include <vector>

using  std::vector;

    关于使用using声明,避免在头文件中进行using声明,以免存在多个文件中都进行了using声明导致重定义等错误。

2.1 定义和初始化

    将类型放在类模板(vector)后的尖括号来指定类型,如下面这个声明表示ivec是保存的是一个int类型的对象:

vector<int> ivec;

    vector对象的初始化方法:

    其中,尖括号的T表示类模板vector所支持的数据类型。在C语言初始化的时候,一般会预先分配合适的空间,但是在C++中,通常是先初始化一个空vector对象,然后再动态地增加元素。

    初始化时,如果没有指定元素的初始化式,则标准库将会自行提供一个元素初始值进行初始化。

2.2 vector对象的操作

    增删查改是最基本的数据操作,书中提到了以下几种vector操作:

    其中,push_back(t)是在vector对象末尾添加一个元素t;size()是获得vector对象的个数。

    查找了其他的资料,找到了删除操作的几个函数,参考博文:[vector删除元素之pop_back(),erase(),remove()](https://blog.csdn.net/dongyanxia1000/article/details/52838922)。使用pop_back()可以删除vector对象的最后一个元素,而采用remove()一般情况下不会改变容器的大小,而pop_back()与erase()等成员函数会改变容器的大小。

2.3 示例

示例说明:初始化vector对象,紧接着使用范围for循环对vector对象进行遍历;使用push_back函数和pop_back函数进行增加对象和删除对象,vector对象也可以使用下标进行访问或操作。如果不了解范围for循环的,可以参考博文:[C++11新特性之基本范围的For循环(range-based-for)](https://blog.csdn.net/hailong0715/article/details/54172848)。

#include <iostream>
#include <vector>


int main() {
	//initial the test_vector: there are 15 integer, and initial value is 10.
	std::vector<int> test_vector(15, 10);

	std::cout << "its size is :"<< test_vector.size() << std::endl;
	//traverse the test_vector 
	for (std::vector<int>::iterator itr = test_vector.begin(); itr != test_vector.end(); itr++) {
		std::cout << *itr << " ";
	}

	//add
	test_vector.push_back(20);
	std::cout << "\nits size is :" << test_vector.size() << std::endl;

	//use subscript to operation
	std::cout << "the last value is :" << test_vector[test_vector.size()-1] << std::endl;

	//delete
	test_vector.pop_back();
	std::cout << "its size is :" << test_vector.size() << std::endl;
	std::cout << "the last value is :" << test_vector[test_vector.size() - 1] << std::endl;

	return 0;

}

示例效果:

its size is :15
10 10 10 10 10 10 10 10 10 10 10 10 10 10 10

its size is :16
the last value is :20
its size is :15
the last value is :10

猜你喜欢

转载自blog.csdn.net/qq_38609565/article/details/107356833