当前位置:网站首页>41.【vector应用操作2】
41.【vector应用操作2】
2022-07-30 06:29:00 【李在奋斗……】
1.【单尾部插入】
函数名.push_back(a), 向尾部插入一个元素a,只能一个个插入,且只能在尾部。
2.【多元插入】 从哪插 插什么
函数名1.insert(函数名1.begin(),a), 向头部插入一个元素a.
函数名1.insert(函数名1.end(),n,a),向尾部插入n个元素 a.
3.【普通数组插入动态数组】
函数名1.insert(函数名1.begin(),普数组名,普数组名+sizeof(普数组名)/sizeof(函数类型))
从哪开始 普通数组首位置,普通数组末位置
4.【单尾部删除元素】
函数名.pop_back() 删除最后一个元素
5.【多元删除】
函数名.(函数名.begin(),函数名.begin()+n)
从哪开始,删除几个.(只能是begin 和end不能换成数字)
6.【for遍历】
for (int i = 0; i < 函数名.size(); i++) //遍历
{
cout << 函数名[i] << " ";
}
7.【迭代遍历】
vector<函数类型>::iterator itor;
for (itor = 函数名.begin(); itor != 函数名.end(); itor++)
{
cout << *itor << " ";
}
===================
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int a[20] = {1,2,3,4,5};
vector<int> str_a; //初始化为空
vector<int> str_a1(4, 88); // 定义四个元素,每个元素的值为88;
vector<int> str_a4(a, a + sizeof(a)/sizeof(int)); //复制正常数组的初始化
int a5 = str_a4[2]; //vector 动态数组的访问,用下标
int b = str_a4.at(2); // 利用at函数,也就是下下标
cout << "a=" << a5 << " " << "b=" << b << endl;
cout << "str_a4的长度为:" << str_a4.size() << endl; //获取长度,
cout << "str_a4的第一个元素为:" << str_a4.front() << endl; // 获取第一个元素
cout << "str_a4的第一个元素为:" << str_a4.back() << endl; //获取最后一个元素
bool p = str_a4.empty(); //判断是否为空
str_a4.swap(str_a1);
str_a4.push_back(100); // 只能向尾部插入元素. 一个一个插入
//str_a.clear(); //对数组元素清空
str_a4.insert(str_a4.begin(), 888); // 从哪插入, 插入什么元素
str_a4.insert(str_a4.begin(),3,888); // 从哪插入, 插入几个 插入什么元素
int szint1[] = { 12,13,45 };
str_a4.insert(str_a4.end(), szint1, szint1 + sizeof(szint1) / sizeof(int));
//str_a4.pop_back(); //删除最后一个元素; 一个一个删除
//str_a4.erase(str_a4.begin(), str_a4.begin()+2); // 从哪开始, 删除几个
//str_a4.erase(str_a4.begin(), str_a4.end());
for (int i = 0; i < str_a4.size(); i++) //遍历
{
cout << str_a4[i] << " ";
}
vector<int>::iterator itor; //迭代器遍历
for (itor = str_a4.begin(); itor != str_a4.end(); itor++)
{
cout << *itor << " ";
}
return 0;
}


边栏推荐
猜你喜欢
随机推荐
Common configuration
Derivative Operations on Vectors and Derivative Operations on Vector Cross and Dot Products
申请内存,std::transform和AVX256指令集用例和执行速度比较
go : 使用gorm创建数据库记录
树状数组的基本用法
Mybitatis related configuration files
Input method for programmers
MySQL basics [naming convention]
What are the access modifiers, declaration modifiers, and keywords in C#?Literacy articles
How does Redis prevent oversold and inventory deduction operations?
Vue2进阶篇-编程式路由导航、缓存路由组件、路由的激活与失活
【COCI 2020/2021 Round #2 D】Magneti (DP)
uniapp中canvas与v-if更“配”
selenium module
C# 使用RestSharp 实现Get,Post 请求(2)
sizeof
【防作弊】Unity防本地调时间作弊
LeetCode:647. 回文子串
stack containing min function (js)
go : 使用gorm查询记录









