Oftentimes, one is working on some specific usecase where they need some kind of behavior associated with a data structure.
For example, one can equip actual vector operations (e.g. dot product) to an stl vector! Then, you can do something like this
std::vector a{5,6}, b{4,6.5};
std::cout << a + b << std::endl;
which wouldn’t work with conventional c++ vectors. However, vect2d, derived from std::vector<double>
, could impose constraints on the length of the data structure, as well as enable this vector addition. I haven’t seen this ever really used elsewhere, but since it isnt immediately obvious, I wanted to share this.
class vec2d: std::vector<double> {
public:
vec2d & operator + (const vec2d & other){
vec2d out{(*this)[0] + other[0], (*this)[1] + other[1]};
return out;
}
};
This actually isnt entirely true. Initializer lists require satisfying an interface beneath the hood, so this current implementation won’t entirely work, though I plan on exploring this in a follow up post soon. This is not even the best use to be sure. A relatively accessible use case is in the case of range operations
#include <algorithms>
#include <iostream>
using namespace std;
class even_vector : public vector<int>
{
public:
void operator()(int n){ if (n % 2 == 0) this->push_back(n); }
};
int main()
{
vector<int> v{1,2,3,4,5,6,7,8,9};
auto out = for_each(begin(v), end(v), even_vector());
for(auto i: out)
cout << i << " ";
return EXIT_SUCCESS;
}
which enables one to capture results in a data structure while performing an opeartion through the range interface.