Collections
-
Prefer
std::dequetostd::vectorwhen the size of the collection is unknow. -
Suppose set
AandBare two set with the same type and setCis another set with the same value type but a different comparison function, then it is still valid to insert results of set operations (union, difference, intersection, symmetric difference and so on) on A and B into setC. It is just that values in C are sorted according to the comparison function ofCnot comparison function ofAandB. -
It is known to all that a set is sorted (according to its comparison function). You cannot sort the set in place using
std::sortwith another comparison function. To sort elements in the set with another comparison function, you have to create a new collection (e.g. a vector), copy the elements over and sort them. -
You can use
std::set::countto check whether a set contains a value or not. -
Removing an element from a set/list/map only affects reference to the remove element not references to other elements. However, removing an element from a vector affects references to elements after the removed elements. A good way to works with vector is to operate on it backwards. That is iterating a vector backwards, removing elements from a vector backwards, etc.
-
std::mapis similar tostd::setfrom many aspect. For example,std::mapcontains values with unique and sorted keys whilestd::setcontains unique and sorted keys.; bothstd::mapandstd::sethave acountmethod which helps to check whether amap/setcontains a key or not; bothstd::mapandstd::sethave afindmethod which helps to find the position of a key in amap/set. Actually, astd::setcan be considered as a special case ofstd::mapwhere the value is of no interest. -
The
std::map::atmethod is preferred over thestd::map::operator[]. -
Associative collections such as
std::mapandstd::sethave methods related binary search (e.g.,countandfind) while sequence collections such asstd::vectorandstd::listdo not have these methods. If a sequence collection is sorted (e.g., usestd::sort), you can apply functionsstd::countandstd::findon it. Sequence collections have methods which can access and modify elements at the front and back of the collection (e.g.,std::front,std::pop_front,std::back,std::pop_back) while associative collections do not have such methods. To access the first and last element of an associative collection, you have to use iterators. For example, to get the last element of a setx, you can use*x.rbegin();
Iterator
-
The difference between points/iterator is of type std::ptrdiff_t, which is essentially a "signed" integer.
-
The result of
std::reverse_iterator::basedecreased by 1 is the corresponding (non-reversed) iterator. For example, if you want to erase the last element from a sets, you can uses.erase(--(s.rbegin().base()));