I saw the following code used to delete one selected element from std::vector
:
vector<hgCoord>::iterator it;
int iIndex = 0;
const int iSelected = 5;
for( it = vecPoints.begin(); it != vecPoints.end(); ++it, ++iIndex )
{
if( iIndex == iSelected )
{
vecPoints.erase( it );
break;
}
}
I argue that this code is not efficient and should be written as follows:
vector<hgCoord>::iterator it;
int iIndex = 0;
const int iSelected = 5; // we assume the vector has more than 5 elements.
vecPoints.erase( vecPoints.begin() + iSelected );
However, I am not sure whether or not this code is following the C++ STL standard.
To make this code generic, so it works no matter whether the iterator supports operator +
, and uses the most efficient available implementation:
template <typename C>
void erase_at(C& container, typename C::size_type index) {
typename C::iterator i = container.begin();
std::advance(i, index);
container.erase(i);
}
Internally, std::advance
uses operator +
if the iterator type supports it. Otherwise (e.g. for std::list<>::iterator
) it advances the iterator one step at a time in a loop, just like the first code you posted.
Random-access iterators support addition and subtraction, and std::vector
iterators are random-access.
You argue correctly :)
That should work fine for a vector because vector iterators are random access iterators, so it's OK to add an offset as you have done. The same won't work for some other container types (such as deque or map).
So, your code is better for a vector, but the other code may have been intended to work with other types of container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With