• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

c++ vector 常用函数示例解析

c++ 搞代码 4年前 (2022-01-06) 26次浏览 已收录 0个评论

这篇文章主要介绍了c++ vector 常用函数示例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

c++ vector 常用函数

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

vector也是一个数组但是它的占用的内存大小是动态变化的。当vector占用的内存满了之后,就要重新分配内存,并且赋值原来的所有元素,为了避免频繁的重新分配内存,迁移数据。vector实际分配的内存比你需要的内存多。比如你有10个int的数据在vector中,vector实际占用的内存是20个int的内存, 当你数据占用超过实际占用内存的比例的时候,vector就会自动重新分配内存,迁移数据. vector实际占用的内存可以用capacity()来查看

 #include #include using namespace std; int main(){ vector ans; for(int i=0; i<10; i++) ans.push_back(i); ans.erase(ans.begin()+2); cout<<"擦除第三个数字:"; for(int j=0; j temp(5, -1); cout<<endl<<"temp的大小为5,默认值是-1:"; for(int l=0; l<temp.size(); l++) cout<<temp[l]<<" "; //resize(int n)改变vector实际储存的数据个数, 如果n比实际个数多,则多出的位添加0,否则截取掉多余数据 temp.resize(8); cout<<endl<<"把temp的大小改变位8:"; for(int h=0; h<temp.size(); h++) cout<<temp[h]<<" "; //在改变vector大小的同时还能指定多余内存的值;这种方式只适用于分配的空间比原来的多的情况 temp.resize(10, 1111); cout<<endl<<"temp的大小改为10,并且指定多出来空间的值位11111:"; for(int g=0; g<temp.size(); g++)cout<<temp[g]<<" "; cout<<endl<<"获取temp的第一个元素:"<<temp.front()<<endl<<"获取temp的最后一个元素:"<<temp.back(); //常用empty()和size函数来判断vector是否为空,当vector为空的时候, empty()返回t<i style="color:transparent">来源gaodai$ma#com搞$$代**码网</i>rue, size()的值为0 return 0;}

此外可以配合#include库中的unique函数来删除vector中的重复元素

 vector ans; ans.erase(unique(ans.begin(), ans.end()), ans.end());

以上就是c++ vector 常用函数示例解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:c++ vector 常用函数示例解析
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址