源码分析
#include <iostream>
#include <vector>
using namespace std;
//vector类型介绍
//1、vector类型简介
//2、定义和初始化vector对象
//3、vector对象上的操作
// (3.1)for循环的进一步理解
int main()
{
//1、vector类型简介:标准库:集合或者是动态数组。可以把若干对象放里边
//vector能把其他对象放进来,所以也称为一种容器
vector<int> vjihe; //表示这个vjihe里边保存的是int型数据(int型对象)
//<int>模板概念
//vector残疾的类类型
//容器套容器
vector<vector<int> > intchuan;
//引用是别名不是对象,不能作为模板参数
// 二、定义和初始化vector对象
// (1)、空vector
vector<string> vmystr;
vmystr.push_back("ab");
// (2)、元素拷贝的初始化方式
vector<string> vmystr2(vmystr);
// (3)、C++11列表初始化
vector<string> mystr4{"aaa","bbb"};
for(auto& ss:mystr4){
cout << ss << endl;
}
//(4)、创建指定数量的元素,有元素数量概念的东西,一般会用圆括号;
vector<int> ijihe(15,-200);
vector<string> sjihe(5,"hello");
vector<int> ijihe2(20);//元素会初始化为0
// (5)、多种初始化方式,()一般代表数量相关,{}元素内容,但不绝对
vector<int> i1(10);
vector<int> i2{10};
vector<string> s1{10}; //会根据类型匹配,这里的10只能代表元素数量
vector<string> s2{10,"hello"}; //会根据类型匹配,这里的10只能代表元素数量
// 想要正确用{}进行初始化,<>模板参数必须与{}里的类型一致
cout << s2.size() << endl;
// 三、vector对象操作,不知道vector里有多少个元素,需要动态增加、减少
// 所以,一般先创建空vector
// vector有很多类似string的操作
vector<int> ivec;
if(ivec.empty()){
cout << "ivec is empty" << endl;
}
//push_back
ivec.push_back(1);
for(auto& aa:{1,2,3,4,5,6,7,8,9,10}){
ivec.push_back(aa);
}
//返回元素个数size
cout << ivec.size() << endl;
//clear
// ivec.clear();
// cout << ivec.size() << endl; //0
//[n]访问第n个元素,n<size
cout << ivec[1] << endl;
cout << ivec[10] << endl;
// cout << ivec[200] << endl; //没有显示错误
// 赋值(=、()、 = {})
// for的应用
vector<int> vecvalue{1,2,3,4,5};
for(auto& vv:vecvalue){ //加&减少赋值拷贝操作
vv *= 2;
}
for(auto& vv:vecvalue){
// 中间不要有其他增加删除等操作
// vecvalue.push_back(77);
cout << vv << endl;
}
return 0;
}