How to Work with Temporary Buffers in C++ - dummies

How to Work with Temporary Buffers in C++

By John Paul Mueller, Jeff Cogswell

Temporary buffers are useful for all kinds of tasks. Normally, you use them when you want to preserve the original data, yet you need to manipulate the data in some way. For example, creating a sorted version of your data is a perfect use of a temporary buffer. The TemporaryBuffer example shows how to use a temporary buffer to sort some strings.

#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
using namespace std;
int main()
{
    vector<string> Words;
    Words.push_back("Blue");
    Words.push_back("Green");
    Words.push_back("Teal");
    Words.push_back("Brick");
    Words.push_back("Purple");
    Words.push_back("Brown");
    Words.push_back("LightGray");
    int Count = Words.size();
    cout << "Words contains: " << Count << " elements." << endl;
    // Create the buffer and copy the data to it.
    pair<string*, ptrdiff_t> Mem = get_temporary_buffer<string>(Count);
    uninitialized_copy(Words.begin(), Words.end(), Mem.first);
    // Perform a sort and display the results.
    sort(Mem.first, Mem.first+Mem.second);
    for (int i = 0; i < Mem.second; i++)
        cout << Mem.first[i] << endl;
    return 0;
}

The example starts with the now familiar list of color names. It then counts the number of entries in vector and displays the count onscreen.

At this point, the code creates the temporary buffer using get_temporary_buffer. The output is pair, with the first value containing a pointer to the string values and the second value containing the count of data elements. Mem doesn’t contain anything — you have simply allocated memory for it.

The next task is to copy the data from vector (Words) to pair (Mem) using uninitialized_copy. Now that Mem contains a copy of your data, you can organize it using the sort function. The final step is to display the Mem content onscreen. Here is what you’ll see:

Words contains: 7 elements.
Blue
Brick
Brown
Green
LightGray
Purple
Teal