跳到主要内容

std::string shrink_to_fit() 方法

// Non const version only
constexpr void shrink_to_fit();

请求移除未使用的容量。
这是一个非绑定请求,用于将 capacity() 减少到 size()
请求是否被满足取决于实现。

失效

如果发生重新分配,所有指针引用迭代器都将失效。

参数

(无)

返回值

(无)

复杂度

容器大小的线性复杂度 - O(size())

异常

(无)

示例

Main.cpp
#include <iostream>
#include <string>

int main()
{
std::string s;
std::cout << "Size of std::string is " << sizeof s << " bytes\n"
<< "Default-constructed capacity is " << s.capacity()
<< " and size is " << s.size() << '\n';
for (int i=0; i<42; i++)
s.append(" 42 ");
std::cout << "Capacity after 42 appends is " << s.capacity()
<< " and size is " << s.size() << '\n';
s.clear();
std::cout << "Capacity after clear() is " << s.capacity()
<< " and size is " << s.size() << '\n';
s.shrink_to_fit();
std::cout << "Capacity after shrink_to_fit() is " << s.capacity()
<< " and size is " << s.size() << '\n';
}
可能输出
GCC output:
Size of std::string is 32 bytes
Default-constructed capacity is 15 and size 0
Capacity after 42 appends is 240 and size 168
Capacity after clear() is 240 and size 0
Capacity after shrink_to_fit() is 15 and size 0

clang output (with -stdlib=libc++):
Size of std::string is 24 bytes
Default-constructed capacity is 22 and size is 0
Capacity after 42 appends is 191 and size is 168
Capacity after clear() is 191 and size is 0
Capacity after shrink_to_fit() is 22 and size is 0
本文档源自 此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”可查看对本文档进行的所有更改。
悬停查看原始许可证。

std::string shrink_to_fit() 方法

// Non const version only
constexpr void shrink_to_fit();

请求移除未使用的容量。
这是一个非绑定请求,用于将 capacity() 减少到 size()
请求是否被满足取决于实现。

失效

如果发生重新分配,所有指针引用迭代器都将失效。

参数

(无)

返回值

(无)

复杂度

容器大小的线性复杂度 - O(size())

异常

(无)

示例

Main.cpp
#include <iostream>
#include <string>

int main()
{
std::string s;
std::cout << "Size of std::string is " << sizeof s << " bytes\n"
<< "Default-constructed capacity is " << s.capacity()
<< " and size is " << s.size() << '\n';
for (int i=0; i<42; i++)
s.append(" 42 ");
std::cout << "Capacity after 42 appends is " << s.capacity()
<< " and size is " << s.size() << '\n';
s.clear();
std::cout << "Capacity after clear() is " << s.capacity()
<< " and size is " << s.size() << '\n';
s.shrink_to_fit();
std::cout << "Capacity after shrink_to_fit() is " << s.capacity()
<< " and size is " << s.size() << '\n';
}
可能输出
GCC output:
Size of std::string is 32 bytes
Default-constructed capacity is 15 and size 0
Capacity after 42 appends is 240 and size 168
Capacity after clear() is 240 and size 0
Capacity after shrink_to_fit() is 15 and size 0

clang output (with -stdlib=libc++):
Size of std::string is 24 bytes
Default-constructed capacity is 22 and size is 0
Capacity after 42 appends is 191 and size is 168
Capacity after clear() is 191 and size is 0
Capacity after shrink_to_fit() is 22 and size is 0
本文档源自 此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”可查看对本文档进行的所有更改。
悬停查看原始许可证。