string::reserve |
public member function |
void reserve ( size_t res_arg=0 ); |
|
Request a change in capacity
Requests that the capacity of the allocated storage space in the string be at least res_arg.
This can expand or shrink the size of the storage space in the string, although notice that the resulting capacity after a call to this function is not necessarily equal to res_arg but can be either equal or greater than res_arg, therefore shrinking requests may or may not produce an actual reduction of the allocated space in a particular library implementation. In any case, it never trims the string content (for that purposes, see resize or clear, which modify the content).
Parameters
- res_arg
- Minimum amount of allocated storage to be reserved.
size_t is an unsigned integral type.
Return Value
none
If the requested size to allocate is greater than the maximum size (string::max_size) a length_error exception is thrown.
Example
// string::reserve
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string str;
size_t filesize;
ifstream file ("test.txt",ios::in|ios::end);
filesize=file.tellg();
str.reserve(filesize);
file.seekg(0);
while (!file.eof())
{
str += file.get();
}
cout << str;
return 0;
}
|
This example reserves enough capacity in the string to store an entire file, which is then read character by character. By reserving a capacity for the string of at least the size of the entire file, we avoid all the automatic reallocations that the object str could suffer each time that a new character surpassed the size of its previously allocated storage space.
Basic template member declaration
( basic_string<charT,traits,Allocator> )
typedef typename Allocator::size_type size_type;
void reserve ( size_type res_arg=0 );
|
See also