STL向量迭代器提供核心转储 [英] STL vector iterator giving core dump

查看:62
本文介绍了STL向量迭代器提供核心转储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream.h>
   #include<vector.h>
   int main()
   {
           vector<int> v;
           vector<int>::iterator itr=v.begin();
           v.insert(itr,10,100);
           v.insert(itr,10,100);
   }

该程序在包含第二次插入后正在生成核心转储,无法理解为什么在第一次插入时itr会增加.

this program is generating core dump after including the second insert,not able to understand why as the itr will be incremented at the time of the first insert.

推荐答案

插入的返回类型对您有利.要解决您的问题,您只需为 itr 重新分配返回值:

Insert has return type in your favor. To fix your problem, you just need to reasign itr with returned value:

vector<int> v;
vector<int>::iterator itr=v.begin();
itr = v.insert(itr,10,100); //new begin
itr = v.insert(itr,10,100); //new begin

另一种解决方法是为向量保留空间:

Another solution is to reserve space for vector:

vector<int> v;
v.reserve(1000);
vector<int>::iterator itr=v.begin();
v.insert(itr,10,100); //itr not invalidated
v.insert(itr,10,100);

这篇关于STL向量迭代器提供核心转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆