Segmentation fault, core dumped error using Vector in CPP

I am getting error : segmentation fault (core dumped) for the below piece of code.. Can anyone help me..??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

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

int main ()
{
 vector <int> v (2);
 vector <int> :: iterator itr=v.begin();
 int i;
 for (i=0; i < v.size(); ++i)
 {
     v.insert(itr, i);
     itr+=1;
  }


for (i=0; i<v.size(); ++i)
{
    cout <<endl <<v[i] ;
}
 return 0;
}
insert may invalidate iterators.

insert increases the reported size of the vector, so aside from the invalidation problem you also have a questionable loop condition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main ()
{
    vector <int> v (5, -1);
    vector <int> :: iterator itr=v.begin();

    const unsigned size = v.size() ;
    for (unsigned i=0; i < size; ++i)
        itr = v.insert(itr, i) + 2 ;

    for ( auto e : v )
    	cout << setw(2) << e << '\n' ;

    return 0;
}


http://ideone.com/fAkQel
Last edited on
You dont need another subscript variable
You can do

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main (int argc, char *argv[])
{
    vector <int> v (2);

    int i=0;
    for (vector <int> :: iterator itr=v.begin(); itr != v.end(); ++itr)
    {
        *itr = i++;
    }

     for (vector <int> :: iterator itr=v.begin(); itr != v.end(); ++itr)
    {
          cout <<endl <<*itr ;
    }
   
   return 0;
}

or for C++11 capable compiler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main (int argc, char *argv[])
{
    vector <int> v (2);

    int i=0;
    for (auto itr=v.begin(); itr != v.end(); ++itr)
    {
        *itr = i++;
    }

     for (auto itr=v.begin(); itr != v.end(); ++itr)
    {
          cout <<endl <<*itr ;
    }
   
   return 0;
}


and if you dont care about the position of numbers then you can also use
1
2
3
4
for (int i=0; i<2; ++i)
{
    v.push_back(i);
}


Also note that I have corrected signature for "main"
Last edited on
Also note that I have corrected signature for "main"


int main() is just as correct as what you "corrected" it to.
Topic archived. No new replies allowed.