A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://cplusplus.com/reference/string/basic_string/reserve/ below:

public member function

<string>

std::basic_string::reserve
void reserve (size_type n = 0);

Request a change in capacity

Requests that the string capacity be adapted to a planned change in size to a length of up to n characters.

If n is greater than the current string capacity, the function causes the container to increase its capacity to n characters (or greater).

In all other cases, it is taken as a non-binding request to shrink the string capacity: the container implementation is free to optimize otherwise and leave the basic_string with a capacity greater than n.

This function has no effect on the string length and cannot alter its content.



Parameters
n
Planned length for the basic_string.
Note that the resulting string capacity may be equal or greater than n.
Member type size_type is an unsigned integral type.

Return Value none

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// string::reserve
#include <iostream>
#include <fstream>
#include <string>

int main ()
{
  std::string str;

  std::ifstream file ("test.txt",std::ios::in|std::ios::ate);
  if (file) {
    std::ifstream::streampos filesize = file.tellg();
    str.reserve(filesize);

    file.seekg(0);
    while (!file.eof())
    {
      str += file.get();
    }
    std::cout << str;
  }
  return 0;
}

This example reserves enough capacity in the basic_string object to store an entire file, which is then read character by character. By reserving a capacity for the basic_string of at least the size of the entire file, we try to avoid all the automatic reallocations that the object str could suffer each time that inserting a new character would make its length surpass its capacity.

Complexity Unspecified, but generally constant.

Iterator validity Any iterators, pointers and references related to this object may be invalidated.

Data races The object is modified.

Exception safetyStrong guarantee: if an exception is thrown, there are no changes in the basic_string.

If n is greater than the max_size, a length_error exception is thrown.


If the type uses the default allocator, a bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also
basic_string::capacity
Return size of allocated storage (public member function)
basic_string::shrink_to_fit
Shrink to fit (public member function)
basic_string::resize
Resize string (public member function)
basic_string::max_size
Return maximum size (public member function)

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4