为什么我的C ++程序崩溃了 [英] Why is my C++ program crashing

查看:111
本文介绍了为什么我的C ++程序崩溃了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在STL中使用向量



我不知道为什么我的程序崩溃。



我尝试过:



I am Learning how to use vectors in STL

I don't know why my program is crashing.

What I have tried:

#include <iostream>
#include<vector>
using namespace std;

int main()
{
    vector<int>vec(10);
    for(int i=0;i<10;i++)
    {
        vec.at(i)=i+1;
        //vec[i]=i+1;
    }
    for(vector<int>::iterator itr=vec.begin();itr!=vec.end();++itr)
    {
        cout << *itr << endl;
    }
    vector<int>::iterator itr1;
    *itr1=vec[4];//PUNGA!
    vec.erase(itr1);
    for(vector<int>::iterator itr=vec.begin();itr!=vec.end();++itr)
    {
        cout << *itr << endl;
    }
}

推荐答案

您正在访问一个unitialised变量(迭代器 itr1 )使用解引用运算符( * )。



让迭代器点到特定的向量元素将索引添加到指向向量开头的迭代器:

You are accessing an unitialised variable (the iterator itr1) with the dereference operator (*).

To let the iterator point to a specific vector element add the index to the iterator pointing to the begin of the vector:
itr1 = vec.begin() + 4;
vec.erase(itr1);





或者使用 advance - C ++ Reference [ ^ ]:



Alternatively use advance - C++ Reference[^]:

itr1 = vec.begin();
std::advance(itr1, 4);
vec.erase(itr1);


这篇关于为什么我的C ++程序崩溃了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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