http://book.douban.com/subject/1456960/
(items on) STL efficiency
Item 1: Choose your containers with care
Item 2: Beware the illusion of container-independent code
Item 3: make copying cheap and correct for objects in containers
Item 4: Call empty() instead of checking size() against zero
Item 5: use range member functions: construction, insertion, erasure, assignment
Item 6: be alert for C++ 's most vexing parse
ifstream dataFile("ints.dat");
istream_iterator<int> dataBegin(dataFile);
istream_iterator<int> dataEnd;
list<int> data(dataBegin, dataEnd); // list<int> data(istream_iterator<int>(dataFile), istream_iterator<int>()); does not work
Item 7: when using containers of "new"ed pointers, remember to "delete" the pointers before the container is destroyed.
(destructor for a pointer doesn't call delete)
or use function objects, where templatization added to the operator ()
struct DeleteObject {
template<typename T> // templatization added here
void operator()(const T* ptr) const {
delete ptr;
}
};
and use it as follows
void doSomething() {
deque<SpecialString*> dssp;
...
for_each(dssp.begin(), dssp.end(), DeleteObject());
}
This piece of code is type-safe, but not exception-safe ==> "smart pointers", e.g., Boost's shared_ptr
Item 8: never create containers of auto_ptrs
(no portability, compilers may fail to compile)
Item 9: choose carefully among erasing options