std::basic_string::shrink_to_fit

std::basic_string::shrink_to_fit

void shrink_to_fit();
(since C++11)

Requests the removal of unused capacity.

It is a non-binding request to reduce capacity() to size(). It depends on the implementation if the request is fulfilled.

If reallocation takes place, all pointers, references, and iterators are invalidated.

Parameters

(none).

Return value

(none).

Complexity

Constant.

Example

#include <iostream>
#include <string>
 
int main()
{
    std::string s;
    std::cout << "Default-constructed capacity is " << s.capacity() << '\n';
    s.resize(100);
    std::cout << "Capacity of a 100-element string is " << s.capacity() << '\n';
    s.clear();
    std::cout << "Capacity after clear() is " << s.capacity() << '\n';
    s.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << s.capacity() << '\n';
}

Output:

Default-constructed capacity is 0
Capacity of a 100-element string is 100
Capacity after clear() is 100
Capacity after shrink_to_fit() is 0

See also

returns the number of characters
(public member function)
returns the number of characters that can be held in currently allocated storage
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/string/basic_string/shrink_to_fit

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部