Pointer Switch

This little parted construct explains quite nicely a case were pointers come in handy. We have two different data containers. A decision is made on which structure we run an algorithm.


Now, the algorithm does not need to care on which structure it is running when we pass the structure as an pointer.  When the condition is evaluated on which structure the algorithm should run, we just assign the structures memory address as value to the pointer.

For showing the essence of the thought the example does not make use of functions. It just shows the body of a single method. Clean code would divide the data structure generation, condition and algorithm.


// Two datastructures of the same type

std::vector vec_a<int>(10, 1);
std::vector vec_b<int>(15, 3); 

// The condition is evaluated and a structures
// memory address is assigned to a pointer.

std::vector<int>* ptr_data = NULL;

bool condition = true;

if ( condition){
    ptr_data = &vec_a;}
    ptr_data = &vec_b;}  

// The algorithm is operating on the choosen structure

for (size_t i = 0; i < ptr_data.size(); i++){
    cout << ptr_data[i] << endl;