In the following code which one is more efficient calling resize or erase ?
vector<int> a(5000);
//....
vector<int>::iterator it = remove(a.begin(),a.end(),8)
a.resize( std::distance(a.begin(),it));
//or
a.erase(it,a.end());
I think it depends on number of duplicate elements right ?
"I think it depends on number of duplicate elements right ?"
Nope. There's no destructor for int
so 1 duplicate or 1000 makes no difference. All either function needs to do is set an internal record of the new end of the in-use elements. Consequently, the performance of remove()
is the costly thing here, not the resize
/erase
. (And even if there was a destructor, they'd loop over the same number of elements calling it, taking almost exactly the same time).
You can almost always trust any seasoned Standard Library implementation not to do something stupid and take far longer than necessary, so given the insight that the behaviours are equivalent - per jrok's answer - there's no reason to investigate further unless your profiler's telling you to.
iter != v.end()
where iterators are implemented as pointers without slower begin+size arithmetic calculations for end()
, nor equally ugly special casing so incrementing an end-1 iterator produces some sentinel state.