vector基础操作
2024-08-22 14:17:03
- //vector< T> vec; //构造一个名为vec的储存数据类型为T的动态数组。其中T为需要储存的数据类型
- //初始时vec为空
- //push_back 末尾添加一个元素
- //pop_back 在末尾弹出一个元素
- //size 获取长度
- size_type size() const; Return size Returns the number of elements in the vector.
- This is the number of actual objects held in the vector, which is not
necessarily equal to its storage capacity.
- //clear 清空
- //修改vector其中的某个元素,直接赋值,比如vec[1]=3; //修改vector其中的某个元素,直接赋值,比如vec[1]=3;
//vector的方法size()可以直接获取长度,通过[]可以直接获取其中的元素,和数组相同
//clear()会清空vector中内容,但是不会重新分配空间
- 如果需要清空vector的内存,一种典型的方法是使用交换, 即使用一个空的vector和原来的vector进行交换,完成内存的释放
vector< int>vec;
{
vector< int> x;
vec.swap(x);
}
- 下面是官方文档关于clear()的描述:
C++官方文档
Clear content
Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:
vector().swap(x); // clear x reallocating
#include<iostream>
#include<vector>
using namespace std;
int main(void)
{
vector<int> vec; //创建动态数组,未知大小
vec.push_back(1); //添加元素1,此时为{1}
vec.push_back(2); //添加元素2,此时为{1,2}
vec.push_back(3); //添加元素3,此时为{1,2,3}
vec[1] = 3; //下标为1的元素被修改为3,此时为{1,3,3}
vec[2] = 2; //下标为2的元素被修改为2, 此时为{1,3,2}
for (int i = 0; i < vec.size(); i++)
printf("%d\n",vec[i]);
return 0;
}
最新文章
- 怎么把Windows主机上的目录共享到Ubuntu上
- 使用AOP 实现多数据源 切换
- IT新人论成长
- launch genymotion simulator from command line
- ECC校验优化之路
- FolderBrowserDialog
- bower的权限问题
- HDU2546:饭卡(01背包)
- 记一次在Tomcat部署项目后无法启动该项目的例子
- CF 224 B Array
- 【笔记】web 的回流与重绘及优化
- BUAA-OO-第二单元总结
- mysql 高版本only_full_group_by 错误
- 个人项目 Individual Project
- TodoMVC:帮助你选择一个MV*框架
- hinton教授的本科生课程CSC321-机器学习中的神经网的笔记
- Ubuntu django+nginx 搭建python web服务器文件日志
- G.Finding the Radius for an Inserted Circle 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛
- Es6 类class的关键 super、static、constructor、new.target
- WPF如何将数据库中的二进制图片数据显示在Image控件上
热门文章
- oracle中时间戳转为Date类型的数据
- SQL:exec sp_executesql 用法
- 【数据库】9.0 MySQL入门学习(九)——获得数据库和表的信息、日期计算、查询、选择特殊列
- jsonp跨域&;百度下拉
- jQuery可调整表和列宽插件-colResizable
- Shader Example
- 编程中遇到的Python错误和解决方法汇总整理
- asyncio标准库7 Producer/consumer
- C# WinForm 程序免安装 .NET Framework(XP/win7/win10环境运行)
- 【Leetcode】【Easy】Length of Last Word