Raw pointers are also Iterators!

Using raw pointers (a.k.a. naked pointers) is never a good first choice. Being high maintenance and error prone creatures, you’re far better off using one of the alternatives offered by the standard library.
Having said that, sometimes you simply do not have a choice. You might be working with a block of memory passed on by a hardware component, or you might be stuck with some critical legacy library that “just works” and nobody dares touch today.
In Any case, using  naked pointer doesn’t mean you have to go full commando yourself. Many of the STL algorithms would accept, with little or no complaints,  raw pointers. an iterator is, after all , a  generalized  pointer:

#include <iostream>
#include <algorithm>
#include <array>
using namespace std;

void PrintArray( int* pBegin, int* pEnd)
	cout << *pBegin++;
	for_each(pBegin, pEnd,[](int i) { cout << ',' << i; } );
	cout << endl << endl;

int main()
	// an integer array
	const auto integer_list =  { 19,14,3,5,20,11,10,18,1,17,9,6,7,2,13,12,4,16,8,15 };
	const size_t block_size = integer_list.size();
	int* pMemBlock = new int[block_size];
	int* pBegin = pMemBlock;
	int* pEnd = (pBegin + block_size);

	//copy the content of the initializer list to the memory block 
	std::copy(integer_list.begin(), integer_list.end(), pBegin);
	cout << "The list of numbers in the memory block:" << endl;
	PrintArray(pBegin, pEnd);

	int count = count_if(pBegin, pEnd, [](int n) {return  n < 5; });
	cout << count  <<  " numbers are less than 5\n" <<  endl;
	std::sort(pBegin, pEnd);
	cout << "sorted list:" << endl;
	PrintArray(pBegin, pEnd);
	cout << endl;
	random_shuffle(pBegin, pEnd);

	cout << "shuffled  list:" << endl;
	PrintArray(pBegin, pEnd);

	delete[] pMemBlock;

The list of numbers in the memory block:

4 numbers are less than 5

sorted list:

shuffled list:

Since the array size is not known at compile time, it’s up to you to accurately calculate the begin and end  pointers (lines 22,23) ,  once these pointers contain the proper addresses,  they can be passed around  just like any other iterator.

note:  if it was a static array, it would have been possible to apply the begin() and end() functions  (overloaded for static arrays by the standard library):

	int arr[]{ 28,4,26,21,20,22,11,12,14,8,17,30,13,15,9,7,19,1,16 };
	cout << "The list of numbers in the static array :" << endl;
	PrintArray(begin(arr), end(arr));

Leave a Reply

Your email address will not be published. Required fields are marked *