Avi Yadav
Avi Yadav

Reputation: 103

C++ function to find minimum from a list . Is this function correct because the returned iterator gets invalidated

list<LNode>::iterator minI(list<LNode>::iterator start,list<LNode>::iterator end)
{
     list<LNode>::iterator min_index=start;

     for(auto it=start;it!=end;it++)
     {
        if(it->len<min_index->len)
            min_index=it;
     }
     return min_index;
}

in main()

..

    cout<<(&(*vnode.begin()))<<endl;
    auto min_it=minI(vnode.begin(),vnode.end());
    cout<<(&(*vnode.begin()))<<endl;
    cout<<(&(*min_it))<<endl;
    char ch;
    int i=min_it->i,j=min_it->j;
    printf("\n%s\t%s\t%s\t%s\t%s\t",t1[i].from,t1[i].to,t1[i].flight,t2[j].city,t2[j].discount);
    scanf("%s",&ch);

    cout<<(&(*min_it))<<endl;

..

while the first three cout prints 0x600d88 the last cout prints 0x600d08 can anyone explain me the reason??

,,

Upvotes: 0

Views: 77

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254451

The iterator doesn't get invalidated.

In general, iterators over standard containers can only be invalidated if the container is modified. In the case of list, they are only invalidated if the element they refer to is removed.

In the second snippet of code, scanf is given a pointer to a single character, but will overwrite at least two: any characters the user enters, followed by the terminator. This gives undefined behaviour, which might well modify the value of local variables (like min_it). Try replacing that with the safer C++ equivalent

std::string ch;
std::cin >> ch;             // to read one word, or 
std::getline(std::cin, ch); // to read a whole line

Upvotes: 2

Related Questions