Applying STL to Legacy Arrays

Explains how to apply STL algorithms to legacy arrays in a minimally invasive way

Introduction

This article shows how to apply STL algorithms to legacy arrays in a way that doesn't require much additional work. By this I mean in a way that doesn't involve copying data from the legacy arrays into an STL vector, or creating custom iterators. "Legacy" in this context refers to the built-in array or MFC's CArray.

Motivation

The motivation for this was some recent C++ maintenance programming I had to do. This code made heavy use of built-in arrays and one or two uses of the MFC CArray. When I first started using STL algorithms I wasn't aware that you could apply them to anything other than STL data structures. This is because my initial source of examples on STL was Visual C++'s online help, which always used STL data structures to illustrate the concepts. Later on I got myself Bjarne Stroustrup's The C++ Programming Language, which provided additional help and then Nicolai Josuttis' The C++ Standard Library. Both of these books explain how you can apply algorithms to built-in arrays but they don't spend much time on it and I more-or-less missed the examples first time around.

Also, I think I'd been using the basic STL data structures with their own member functions for some time before I learnt how to use the general-purpose algorithms. And, of course, since built-in arrays don't have member functions the question of manipulating them didn't arise. When I finally discovered algorithms my primary focus was in applying them to newly written code. In that context I was pretty much always going to start off with an STL data structure so, again, the issue of built-in arrays did not arise.

MFC CArray

You can apply algorithms quite easily to MFC's CArray class too. There is a function, GetData(), that returns a pointer to the first array element in the CArray. Try adding the following code to, say, the OnInitDialog() member in the dialog class of an MFC dialog-based application and run it in the debugger.

We cannot apply this technique to a CList. For this we need to create a custom iterator. And in fact we ought to do the same for a CArray. I believe there is an example of how to do this somewhere on the CodeGuru web site: http://www.codeguru.com/. But the above technique provides a quick and dirty way of applying the power of STL in a minimally invasive way.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.