c++ - Expected return of find STL algorithm -
list< int > a; list < int > ::iterator it; = a.begin(); it=a.insert(it,10); it=a.insert(it,210); it=a.insert(it,310); it=a.insert(it,410); it=a.insert(it,510); = find(a.begin(),a.end(),180); cout << *it << endl; in program value 180 not present in list. per find stl algorithm should return last value, when print value coming garbage. seems iterator pointing other location. please me spot error.
std::find returns end() if element not found in stl container, dereference end() undefined behavior.
you need test iterator it before dereference it:
it = find(a.begin(), a.end(), 180); if (it != a.end()) { cout << *it << endl; } § 25.2.5
returns: first iterator in range [first,last) following corresponding conditions hold: *i == value, pred(*i) != false, pred(*i) == false. returns last if no such iterator found.
range [first,last) half open range, last means end() not last element in container.
Comments
Post a Comment