Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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;
    }
}
Posted
Updated 4-Jul-16 4:23am
v2

1 solution

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:
C++
itr1 = vec.begin() + 4;
vec.erase(itr1);


Alternatively use advance - C++ Reference[^]:
C++
itr1 = vec.begin();
std::advance(itr1, 4);
vec.erase(itr1);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900