求解STL中的一些问题????

我菜就爱学
全栈领域新星创作者
2019-07-25 02:49:40
vector容器中使用完v.clear(),为什么之后输出的数组v[1]中还有值呢?不是清空了吗?
...全文
90 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
我菜就爱学 2019-07-25
  • 打赏
  • 举报
回复
引用 5 楼 林多 的回复:
谢谢啦
林多 2019-07-25
  • 打赏
  • 举报
回复
clear只会清空容器,让容器的size为零。 但是不能保证,释放已经分配的内容。 vector clear接口的英文解释。 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<T>().swap(x); // clear x reallocating ----------------------------------- 所以说,还有很值很正常。。容器所申请的内存,没有重新配置。。V[0]、V[1]、V[2]所对应的内存地址中,值还是存在的。

#include<vector>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
vector<int> v(10);
for(int i=0;i<10;i++)
v[i]=i;
v.clear();//清空 
cout<<v.size()<<endl;
cout<<v.capacity()<<endl; // 输出10,申请的内存空间 没有发生重分配
cout<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<endl;

// 释放内存空间
vector<int>().swap(v);
// Crash,输出非法地址
// cout << v[0] <<endl;

return 0;
}
我菜就爱学 2019-07-25
  • 打赏
  • 举报
回复
Dev-c++5.11
真相重于对错 2019-07-25
  • 打赏
  • 举报
回复
你的编译器版本?
我菜就爱学 2019-07-25
  • 打赏
  • 举报
回复
引用 1 楼 真相重于对错 的回复:
贴出具体代码?
#include<vector> #include<stdlib.h> #include<iostream> #include<algorithm> using namespace std; int main() { vector<int> v(10); for(int i=0;i<10;i++) v[i]=i; v.clear();//清空 cout<<v.size()<<endl;//长度 cout<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<endl; return 0; }
真相重于对错 2019-07-25
  • 打赏
  • 举报
回复
贴出具体代码?

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧