S
Steve555
In the case where lower_bound() doesn't find the value, my book
(O'Reilly STL) states "...the iterator points to the position of the
first item greater than the value.
In my code I check that the value doesn't exist, but the iterator
points to it anyway!:
MovieRatingVector::iterator iter;
for(iter = mMovieRatings.begin(); iter != mMovieRatings.end(); ++iter)
{
thisMovieID = (*iter).movieID;
thisRating = (*iter).rating;
cout << thisMovieID<< " "<< thisRating<<endl;
}
Produces:
457 3
3151 1
11607 3
12155 3
12911 4
This is correct.
Then, suspecting a problem, immediately I test for movieID = 16469
(which I know ISN'T there)
MovieRating pair;
pair.movieID = 16469;
pair.rating = 0;
iter = std::lower_bound(mMovieRatings.begin(), mMovieRatings.end(),
pair);
cout<< (*iter).movieID << " "<<(*iter).rating;
Produces:
16469 3
What's happened? Has it just happened to find the value 16469 in an
adjacent block of memory?
And even if it has, why return it? How do I guard against this?
I don't know if it's just lucky coincidence, but the following worked
on the first first few thousand such checks without error: (I expected
that, per O'Reilly, it would be pointing to a value greater than my
value, NOT equal)
if((*iter).movieID == inMovieID)
return outRating;
else
return 0;
(O'Reilly STL) states "...the iterator points to the position of the
first item greater than the value.
In my code I check that the value doesn't exist, but the iterator
points to it anyway!:
MovieRatingVector::iterator iter;
for(iter = mMovieRatings.begin(); iter != mMovieRatings.end(); ++iter)
{
thisMovieID = (*iter).movieID;
thisRating = (*iter).rating;
cout << thisMovieID<< " "<< thisRating<<endl;
}
Produces:
457 3
3151 1
11607 3
12155 3
12911 4
This is correct.
Then, suspecting a problem, immediately I test for movieID = 16469
(which I know ISN'T there)
MovieRating pair;
pair.movieID = 16469;
pair.rating = 0;
iter = std::lower_bound(mMovieRatings.begin(), mMovieRatings.end(),
pair);
cout<< (*iter).movieID << " "<<(*iter).rating;
Produces:
16469 3
What's happened? Has it just happened to find the value 16469 in an
adjacent block of memory?
And even if it has, why return it? How do I guard against this?
I don't know if it's just lucky coincidence, but the following worked
on the first first few thousand such checks without error: (I expected
that, per O'Reilly, it would be pointing to a value greater than my
value, NOT equal)
if((*iter).movieID == inMovieID)
return outRating;
else
return 0;