C++入门笔记:Vectors

关于Vectors

Similar to java ArrayList.

  1. C++的standard template library提供vector数据类型,而vector是一种container
    container分为两种,sequence container将数据像array一样排列好;而associate container可以让程序员直接获得elements stored in the container。container分为两种,sequence container将数据像array一样排列好;而associate container可以让程序员直接获得elements stored in the container。

  2. 关于定义一个 STL vector
    一定要有vector的头文件,在定义的时候不需要设置大小,依然可以用array的[]来读取vector里的element。

Expression意义
vector < int > numbers;此情况没有强调长度
vector < int > numbers (10);初始化长度为10
vector < int > numbers(10, 2);定义了一个长度为10,每一项初始值都为2
vector < int > set2 (set1);set2是a copy of set1
vector < int > numbers { 10, 20, 30, 40 };C++ 11 Only。注意要用 { }, 而且没有等于号
  1. 一些vector的方程:
Vector方程意义
x = vect.at(5);assigns the value of the 5th element of vect to x
x = vect.capacity();跟size()不一样,capacity意味着在不新allocate内存都时候,这个vect可以存多少个element
x = vect.size();vect里面已经有多少个element了
vect.clear();把vect里面都element全部清空
vect.empty()返回一个boolean值,检查这个vector是不是空的
vect.pop_back();把vect最后的element去除,这时候vect的长度也会减一
vect.push_back(7);在vect最后加入7这个值,如果vect是空的或者满的,a new element then will be created
vect.reverse();把一个vector的顺序打乱,1234 -> 4321
vect.resize(n, m);把vect重新调整大小,变成n长度, 每一项都是initialize成m
vect1.swap(vect2);把vect1 和 vect2的内容相交换

练习:
Write a single statement that assigns a new value to the element of the vector indexed by j. This new value should be equal to twice the value stored in the next element of the vector (i.e. the element after the element indexed by j).Do not modify any other elements of the vector! (From: codelab)
答案: a.at(j) = 2 * a.at(j+1);

Reference: Gaddis, Tony. Starting out with C++ . Pearson, 2019.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值