Reputation: 99
I am testing std::list with a find() function from . Before I implement it into my program, I want to see if they will work just as I think they do. At first it worked well: `
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(9);
list<int>::iterator it = find(l.begin(), l.end(), 9);
if (*it == 9)
{
cout << "Found";
}
else
{
cout << "Not Found";
}
In this example, output was "Found", that is right, but when I do it like this:
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(9);
list<int>::iterator it = find(l.begin(), l.end(), 3);
if (*it == 9)
{
cout << "Found";
}
else
{
cout << "Not Found";
}
It doesn't output anything, but it should output "Not Found", i get a "Debug Assertion Failed!" error, it says that "Expression: list iterator not dereferencable", how i can fix this problem?
Upvotes: 0
Views: 1078
Reputation: 227418
std::find
returns the end()
iterator when something is not found in a container. And de-rererencing the end()
iterator as you do here:
if (*it == 9)
is undefined behaviour. To see if you found an element, check against the end iterator:
if (it != l.end())
{
cout << "found\n";
}
Upvotes: 6