Search code examples
c++vectorstlsegmentation-faultconst-iterator

segmentation fault for vector iterator


why is this code producing a segmentation fault when i try to output the value ?
the segmentation fault is being caused due to the line

cout << *rit_j;

void chef(vector<int>vec)
{
    int count=0;
    vector<int>::iterator bit = vec.begin();
    vector<int>::iterator eit=vec.end();
    if(*bit != *eit)
    {
        sort(bit,eit);          
        vector<int>::iterator rit_i,rit_j,initial = vec.end();
        --rit_i;--rit_j;--initial;
        cout << *rit_i;

     }
 }

Solution

  • In this declaration:

    vector<int>::iterator rit_i,rit_j,initial = vec.end();
    

    only initial is initialized with vec.end(). To make it do what I think you expect, you have to write

    vector<int>::iterator rit_i = vec.end(), rit_j = vec.end(), initial = vec.end();
    

    or

    vector<int>::iterator rit_i,rit_j,initial;
    rit_i = rit_j = initial = vec.end();
    

    or something to that effect.