Tuesday, December 04, 2007

C++ Programming Tips

Inserting into a sorted std::vector

if (MyVec.size() > 1)
MyVec.begin() + (MyVec.size() - 2),

This won't be the fastest way of performing an insert, but it will probably be the smallest amount of code. For the fastest way, look at finding with a binary search, then inserting.

Disclaimer: If you are going to be inserting many things into the middle of a vector, you probably shouldn't be using a vector. A list would be more suited.

Constructor variable initialisation order

This is a subtle C++ism that I forgot about and caught me out today.

When initialising items in a constructor's initialisation list, the order of initialisation is dependant on the order the variables appear in the class definition, not the initialisation list.

An example will help:

class MyClass

int a;
int b;
int c;

MyClass::MyClass() :
b(0), c(0), a(0)

In the above example, a, will be initialised first followed by b, then c.

1 comment:

Alta Noble said...

These are very helpful tips on C++ programming. Thanks for sharing a very informative article.