Why isn’t there an operator[] for a std::list?

Retrieving an element by index is an O(n) operation for linked list, which is what std::list is. So it was decided that providing operator[] would be deceptive, since people would be tempted to actively use it, and then you’d see code like: std::list<int> xs; for (int i = 0; i < xs.size(); ++i) { int … Read more

Can I use const in vectors to allow adding elements, but not modifications to the already added?

Well, in C++0x you can… In C++03, there is a paragraph 23.1[lib.containers.requirements]/3, which says The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types. This is what’s currently preventing you from using const int as a type argument to std::vector. However, in … Read more

What C++ pitfalls should I avoid? [closed]

A short list might be: Avoid memory leaks through use shared pointers to manage memory allocation and cleanup Use the Resource Acquisition Is Initialization (RAII) idiom to manage resource cleanup – especially in the presence of exceptions Avoid calling virtual functions in constructors Employ minimalist coding techniques where possible – for example, declaring variables only … Read more

C++ inserting unique_ptr in map

As a first remark, I wouldn’t call it ObjectArray if it is a map and not an array. Anyway, you can insert objects this way: ObjectArray myMap; myMap.insert(std::make_pair(0, std::unique_ptr<Class1>(new Class1()))); Or this way: ObjectArray myMap; myMap[0] = std::unique_ptr<Class1>(new Class1()); The difference between the two forms is that the former will fail if the key 0 … Read more

Sorting a list of a custom type

You can specify a custom sort predicate. In C++11 this is best done with a lambda: typedef std::pair<int, int> ipair; std::list<ipair> thelist; thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; }); In older versions of C++ you have to write an appropriate function: bool compFirst(const ipair & a, const ipair … Read more