There are such cases when we need to store pointers in the container. The examples are: storing polymorphic data in containers, forcing fast copy of data in containers, and strict exception requirements for operations with data in containers. In such cases, C++ programmer has the following choices:
- Store pointers in containers and take care of their destructions using delete:
#include <set>
#include <algorithm>
#include <cassert>
template <class T>
struct ptr_cmp {
template <class T1>
bool operator()(const T1& v1, const T1& v2) const {
return operator ()(*v1, *v2);
}
bool operator()(const T& v1, const T& v2) const {
return std::less<T>()(v1, v2);
}
};
void example1() {
std::set<int*, ptr_cmp<int> > s;
s.insert(new int(1));
s.insert(new int(0));
// ...
...