Home

How to Work with Temporary Buffers in C++

|
Updated:  
2016-03-26 08:30:01
|
From The Book:  
C++ Essentials For Dummies
Explore Book
Buy On Amazon

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

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.