November 27, 2008
What’s the best way to erase one or more elements from an STL container? By ‘best’ let’s go with performance as the first priority, followed by code reuse and C++ standard-compliance/portability.
Also, like all good developers we’ve profiled our code and have determined that yes, it’s worthwhile spending time trying to optimise this erasure.
So I did some tests and am happy to report that the STL algorithms kick ass.
If there’s only 1 element to be erased, then the best (as defined above) method is erase-find:
vector<int> v;
v.erase( find(v.begin(), v.end(), 5) );
(Or substitute another find algorithm, such as find_if.)
If there is 1 or more elements to be erased then go with erase-remove:
vector<int> v;
v.erase( remove(v.begin(), v.end(), 5) );
(Again, other remove algorithms can be used.)
The STL algorithms should be preferred over a custom loop and condition, as the following graph illustrates:

(Click to view at 100%.)
Note that the graph shouldn’t be used to compare the performance between containers or elements. Rather, the graph only illustrates the performance of erase methods for a variety of containers.
Erase-remove performs about the same, and in some cases better, than a custom loop and condition (even when it breaks out of the loop once the element is found), which is quite impressive really. But for a single element nothing can beat erase-find.
Leave a Comment » |
C++ |
Permalink
Posted by neilhendo
November 25, 2008
One of D’s major differences from C++ is to do with classes and their private members.
In D, any code in the same module as a class can access that class’ private members. An example is probably useful:
module example.Dogsarama;
class Dog
{
public:
this(int age)
{
m_age = age;
}
int Age()
{
return m_age;
}
void SetAge(int age)
{
m_age = age;
}
private:
int m_age;
}
void SetDogAge(Dog d, int age)
{
// I can access this dog's privates!!!
d.m_age = age;
}
Because SetDogAge() is part of the same module as the Dog class, it is entitled to access and manipulate Dog’s private members.
So in another module we can do this:
module example.Main;
import std.stdio;
import example.Dogsarama;
int main(char[][] args)
{
auto fido = new Dog(15);
SetDogAge(fido, 17);
writeln(fido.age());
return 0;
}
Though I had read the main parts of the D spec I only discovered this by experimenting. I later found the appropriate documentation which is unfortunately a bit obscure, IMO.
1 Comment |
C++, D |
Permalink
Posted by neilhendo
November 12, 2008
“Obama and the War on Brains”
Excerpt:
Barack Obama’s election is a milestone in more than his pigmentation. The second most remarkable thing about his election is that American voters have just picked a president who is an open, out-of-the-closet, practicing intellectual.
Leave a Comment » |
Politics |
Permalink
Posted by neilhendo