vector使用出了个问题,谁给解释下?

hongss 2019-04-08 11:55:45
	vector<int> v_Org;
v_Org.clear();
for(int i=0; i<10; i++)
{
v_Org.push_back( i + 1 );
}
Mmo_1->Lines->Add( "v_Org Size = " + AnsiString( (int)v_Org.size() ) );
v_Org.clear();
Mmo_1->Lines->Add( "v_Org Size = " + AnsiString( (int)v_Org.size() ) );
vector<int> v_Chd;
v_Chd.clear();
v_Chd.assign( v_Org.begin()+3, v_Org.begin()+7 );
Mmo_1->Lines->Add( "v_Chd Size = " + AnsiString( (int)v_Chd.size() ) );


输出结果
v_Org Size = 10
v_Org Size = 0
v_Chd Size = 4

为什么?v_Org已经清空,这v_Chd里的数据哪里来的?
...全文
279 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
hongss 2019-04-09
  • 打赏
  • 举报
回复
看来只能这样了。。。结贴了,慢慢研究吧~~~
stherix 2019-04-08
  • 打赏
  • 举报
回复
因为你强行把v_Chd设置为v_Org的其中一段 导致其计算大小变成了4 理论上这段代码应该是不能正常运行的(在标准c++里面) 可能是bcb的编译器没有做严格的检查
  • 打赏
  • 举报
回复
erase只是把vector的size设置为0,不保证重新分配空间(取决于实现),所以之前的数据可能仍然存在(但是不应该认为其有效)
hongss 2019-04-08
  • 打赏
  • 举报
回复
这vector不就是个幽灵般的存在。。。明明擦除的数据,又可以赋给其他变量
  • 打赏
  • 举报
回复
判断范围是否在vector::size之内即可
hongss 2019-04-08
  • 打赏
  • 举报
回复
那么,像这样的截取数据,还得在截取前判断源vector是不是空么?
hongss 2019-04-08
  • 打赏
  • 举报
回复
Win7 + XE2
  • 打赏
  • 举报
回复
std::vector::clear

C++98
C++11

void 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
stherix 2019-04-08
  • 打赏
  • 举报
回复
引用 5 楼 hongss 的回复:
<vector> vector::clear void clear(); The member function calls erase( begin(), end()).
不同编译器实现可能完全不一样 不知道你用的什么编译器 如果是bcb的话,可能是有点问题的 因为vector清空后,取begin()+3肯定是要报错的,然而看你的代码并没有,begin()+7也一样 所以照样能获取到原来的数据哪也不奇怪了
hongss 2019-04-08
  • 打赏
  • 举报
回复
<vector> vector::clear void clear(); The member function calls erase( begin(), end()).
stherix 2019-04-08
  • 打赏
  • 举报
回复
v_Org.clear之后 v_Org.begin()+3 应该会报错 另外清空一个vector只是把索引器设置成和begin相等,并不一定要删除其中的数据
hongss 2019-04-08
  • 打赏
  • 举报
回复
他们的内容还是没有v_Org.clear时的, v_Org = 1 2 3 4 5 6 7 8 9 10 v_Org Size = 10 v_Org Size = 0 v_Chd Size = 4 v_Chd = 4 5 6 7
hongss 2019-04-08
  • 打赏
  • 举报
回复
我的本意是要从已有的v_Org中,截取设定位置的数据到v_Chd里,以方便我对取到的v_Chd里的数据进行处理 这里,好像对v_Org的清空不存在一样,这是为什么?谁能给解释下?

13,871

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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