c++中vector向量的一些主要问题

本文探讨了C++ STL中vector的const_iterator使用时遇到的vectoriteratornotdereferencable错误。通过示例代码展示了在对容器进行修改后使用const_iterator的潜在问题,并提供了正确的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近日,用到c++ STL中vector,浏览到关于出现 “_DEBUG_ERROR("vector iterator not dereferencable") “问题的一帖子:
C++标准库assign()   链接:http://wenwen.soso.com/z/q165763904.htm 该帖子上的问题与我出现的问题相符,所以进一步进行了跟踪。引用该帖子中部分代码如下:

#include <vector>
#include <iostream>
using namespace std;
void exciseVector(void)
{
vector<int> vec1(100);
vector<int> vec2(10, 10);
vector<int>::const_iterator it = vec1.begin();
vec1 = vec2;
//vec1.push_back(9);
cout<<vec1.size()<<", "<<vec1.capacity()<<endl;
cout<<(*it)<<endl;
}


int main(void)
{
exciseVector();
return 0;
}
当单步执行到语句"cout<<vec1.size()<<", "<<vec1.capacity()<<endl;"时输出结果为 :10, 100,当执行到语句” cout<<(*it)<<endl;“时提示:”Dobug Assertion Failed! vector iterator not dereferencable"。
跟踪源码,会定位到” #if _HAS_ITERATOR_DEBUGGING
if (this->_Mycont == 0
|| _Myptr < ((_Myvec *)this->_Mycont)->_Myfirst
|| ((_Myvec *)this->_Mycont)->_Mylast <= _Myptr)
{
_DEBUG_ERROR("vector iterator not dereferencable");
_SCL_SECURE_OUT_OF_RANGE;
}“
 语句,原因是当运用迭代器const_iterator 后,是不能对该容器中的成员做修改,只能访问。在上面程序中,语句”vec1 = vec2“或"vec1.push_back(9)"对容器做了修改,致使违法了const_iterator迭代器的使用规则而报错。


将上面代码作如下修改即可编译通过:
#include <vector>
#include <iostream>
using namespace std;
void exciseVector(void)
{
vector<int> vec1(100);
vector<int> vec2(10, 10);

vec1 = vec2;
//vec1.push_back(9);
vector<int>::const_iterator it = vec1.begin();
cout<<vec1.size()<<", "<<vec1.capacity()<<endl;
cout<<(*it)<<endl;
}


int main(void)
{
exciseVector();
return 0;
}

运行结果:

10,100
10
代码修改后,由于对向量的"vec1 = vec2"或"vec1.push_back(9)"是在迭代器const_iterator前操作,在用迭代器const_iterator时,只是对其进行了访问而没有做修改操作,因此可以编译。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值