前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vector基础操作

vector基础操作

作者头像
Enterprise_
发布2019-02-21 17:08:51
5710
发布2019-02-21 17:08:51
举报
文章被收录于专栏:小L的魔法馆
  • //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进行交换,完成内存的释放
代码语言:javascript
复制
vector< int>vec;
{
vector< int> x;
vec.swap(x);
}

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

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年09月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档