Using vector to improve memory redistribution in C + + STL

Source: Internet
Author: User
Tags include int size

This article describes a very common scenario: when you store data in a cache, you often need to resize the cache at run time to accommodate more data. This article discusses how to use an STL vector for memory redistribution.

This is a very common scenario: when you store data in a cache, you often need to resize the cache at run time to accommodate more data. Traditional memory redistribution is cumbersome and error-prone: in C, it is common to call realloc () every time you need to expand the cache. Worse in C + +, you can't even reapply the memory for an array of the new operations in the function. Not only do you have to do the allocation process yourself, but you must also copy the data from the original cache to the new destination cache, and then release the cache of the previous array. This article will provide a secure, easy, and automated C + + memory redistribution technique for this issue-that is, using an STL vector.

It is safe, simple, and automated to replace the built-in array with the STL vector object to save the acquired data.

Further analysis of the problem

Before proposing the solution, let me give a concrete example to illustrate the drawbacks and complexities of C + + reallocation of memory. Suppose you have a catalog application that reads the user-entered ISBNs and inserts it into an array until the user enters 0. If the user inserts more data than the capacity of the array, then you must increase its size accordingly:

#include < iostream>
using namespace std;
int main()
{
 int size=2; // 初始化数组大小;在运行时调整。
 int *p = new int[size];
 int isbn;
 for(int n=0; ;++n)
 {
  cout<< "enter an ISBN; press 0 to stop ";
  cin>>isbn;
  if (isbn==0)
   break;
  if (n==size) // 数组是否到达上限?
   reallocate(p, size);
    p[n]=isbn; // 将元素插入扩容的数组
 }
 delete [] p; // 不要忘了这一步 !
}

Note how cumbersome this process of inserting data into an array is. Each iteration, the loop checks to see if the cache is up to the upper limit. If so, the program invokes the user-defined function reallocate (), which implements the following:

#include <algorithm> // for std::copy
int reallocate(int* &p, int& size)
{
 size*=2; // double the array''s size with each reallocation
 int * temp = new int [size];
 std::copy(p, p+(size/2), temp);
 delete [] p; // release original, smaller buffer
 p=temp; // reassign p to the newly allocated buffer
}

Reallocate () uses the STL std::copy () algorithm to make a reasonable expansion of the cache--one-fold magnification for each expansion. This approach avoids allocating too much memory in advance, reducing the amount of memory that needs to be reassigned. This technology needs to be fully tested and debugged, especially when the scholar realizes it. In addition, reallocate () is not generic, it can only handle the case of an integer array. For other data types, it does nothing, you have to define the additional version of the function or template it. Fortunately, there is a more ingenious way to achieve it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.