Collections
-
Prefer
std::deque
tostd::vector
when the size of the collection is unknow. -
Suppose set
A
andB
are two set with the same type and setC
is 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 ofC
not comparison function ofA
andB
. -
It is known to all that a set is sorted (according to its comparison function). You cannot sort the set in place using
std::sort
with 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::count
to 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::map
is similar tostd::set
from many aspect. For example,std::map
contains values with unique and sorted keys whilestd::set
contains unique and sorted keys.; bothstd::map
andstd::set
have acount
method which helps to check whether amap/set
contains a key or not; bothstd::map
andstd::set
have afind
method which helps to find the position of a key in amap/set
. Actually, astd::set
can be considered as a special case ofstd::map
where the value is of no interest. -
The
std::map::at
method is preferred over thestd::map::operator[]
. -
Associative collections such as
std::map
andstd::set
have methods related binary search (e.g.,count
andfind
) while sequence collections such asstd::vector
andstd::list
do not have these methods. If a sequence collection is sorted (e.g., usestd::sort
), you can apply functionsstd::count
andstd::find
on 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::base
decreased 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()));