前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ Vector Resize函数[通俗易懂]

C++ Vector Resize函数[通俗易懂]

作者头像
全栈程序员站长
发布2022-07-23 16:47:33
1.4K0
发布2022-07-23 16:47:33
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

C++ Vector Resize函数

Change size Resizes the container so that it contains n elements. If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them). If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized. If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place. Notice that this function changes the actual content of the container by inserting or erasing elements from it.

void resize (size_type n, value_type val = value_type());

改变vector容器的大小。

改变容器的大小使他包含 n n n个元素。

  • 如果 n n n 小于当前容器大小,则内容减少到前 n n n个元素,移除后面的元素。
  • 如果 n n n 大于当前容器大小,则在后面插入一些元素至 n n n个大小,如果 v a l val val被定义则插入 v a l val val的复制,否则插入默认值 0 0 0。
  • 如果 n n n大于当前容器的容量 ( c a p a c i t y ) (capacity) (capacity),则自动进行内容重新分配。

实例

代码语言:javascript
复制
// resizing vector
#include <iostream>
#include <vector>

int main ()
{ 
   
  std::vector<int> myvector;

  // set some initial content:
  for (int i=1;i<10;i++) myvector.push_back(i);

  myvector.resize(5);
  myvector.resize(8,100);
  myvector.resize(12);

  std::cout << "myvector contains:";
  for (int i=0;i<myvector.size();i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

结果

代码语言:javascript
复制
myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/126842.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年4月8,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C++ Vector Resize函数
    • 实例
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档