Use the right container
Sequence containers
- Do not use
vector
for data of unknown size if you are going to keep adding data to it. If you are going to repeatedly call push_back()
, either use reserve()
or use a deque
instead.
- If you are going to be adding/removing data in the middle of the container,
list
is probably the right choice.
- If you are going to be adding/removing data from both ends of the container,
deque
is probably the right choice.
- If you need to access the nth element of the container,
list
is probably the wrong choice.
- If you need to both access the nth element of the container and add/remove elements in the middle, benchmark all three containers.
- If you have C++0x capability and are using a
list
but you never move backwards through the list, you may find forward_list
more to your liking. It won't be faster but it will take up less space.
Note that this advice becomes more applicable the larger the container. For smaller containers, vector
may always be the right choice simply because of the lower constant factors. When in doubt, benchmark.
Associative containers
- If you do not have TR1, C++0x, or a vendor-specific
unordered_foo
/hash_foo
, there isn't a ton of choice. Use whichever of the four containers is appropriate to your needs.
- If you do have an
unordered_foo
, use it instead of the ordered version if you do not care about the order of the elements and you have a good hash function for the type.
Use exceptions judiciously
- Don't use exceptions in your normal code path. Save them for when you actually have an exceptional circumstance.
Love templates
- Templates will cost you at compile time and space-wise, but the performance gains can be amazing if you have calculations that would otherwise be performed at run-time; sometimes even something so subtle as a downcast.
Avoid dynamic_cast
dynamic_cast
is sometimes the only choice for doing something, but oftentimes the use of dynamic_cast
can be eliminated by improving design.
- Don't replace
dynamic_cast
with a typeid
followed by a static_cast
either.