Re: std::vector Question
On Wednesday, 3 July 2013 05:05:13 UTC+1, Mike Copeland wrote:
In the following code (which seems to work), I must decrement the
vector offset (mmm) when I declare the iterator I use to delete an
object. Can someone explain why, even though I can address the object
(in the for loop) directly?
Or is there a better way to do this? TIA
vector<time_t> scoreTimes;
bool bFound = false;
size_t mmm;
time_t delT1 = [some_value], delT3;
for(mmm = 0; mmm < scoreTimes.size(), bFound == false; mmm++)
{
if(scoreTimes.at(mmm) == delT1) bFound = true;
} // for
The obvious problem here is that you increment mmm one last time
after having set bFound to true. (And while I'm at it: you
never compare a variable with true or false. It should be just
!bFound. And you probably don't want the comma operator there,
either; the compiler should have warned you, but you just throw
away the results of "mmm < scoreTimes.size()", which will cause
problems if delT1 isn't in scoreTimes.)
This is just a linear search. The classic way of writing this
would be something like:
for ( mmm = 0;
mmm != scoreTimes.size() && scoreTimes[mmm] != delT1;
++ mmm ) {
}
And to test whether you've found something:
if ( mmm != scoreTimes.size() )
In modern C++, we'd probably use std::find:
std::vector<time_t>::iterator position
= std::find( scoreTimes.begin(), scoreTimes.end(), delT1 );
and then, if you needed mmm:
ptrdiff_t mmm = position - scoreTimes.begin();
but you probably don't need it, since...
if(bFound) // found object to delete
{
vector<time_t>::iterator vIt = scoreTimes.begin()+(--mmm); //???
delT3 = *vIt;
scoreTimes.erase(vIt);
}
If you've used std::find, above, all you need to do is
if ( position != scoreTimes.end() ) {
delT3 = *position;
scoreTimes.erase( position );
}
--
James