如何在vector::clear()上保持向量元素的容量

How to preserve capacity of vector elements on vector::clear()?

本文关键字:向量 元素 容量 vector clear      更新时间:2023-10-16

清除vector<string>时,会保留vector的容量,但不会保留向量中单个string的容量。有办法做到这一点吗?

我想不出一种简单明了的方式来实现这一点。下面是一些测试代码,演示了我要做的事情:

#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
istringstream input;
input.str(
R"(2
This is the first sentence.
And this is the second sentence.
3
Short text.
Another short text.
The end!
)");
vector<string> lines;
string line; // The capacity of this string is preserved throughout.
while (getline(input, line))
{
int count = stoi(line);
lines.clear(); // This clears capacity of the string elements too!
for (int i = 0; i < count; ++i)
{
getline(input, line);
lines.push_back(line);
}
// process/print 'lines' here.
}
return 0;
}

保持string元件的容量的一种方法是从不清除vector,并手动跟踪vector的大小。但那根本就不干净。这个问题有干净的解决方案吗?

编辑:

如果我按照以下方式重新排列代码,我就可以保留向量中字符串的容量。然而,这是非常丑陋的。我正在寻找一个干净的解决方案。

...
vector<string> lines;
string line; // The capacity of this string is preserved throughout.
while (getline(input, line))
{
int count = stoi(line);
for (int i = 0; i < count; ++i)
{
if (i < lines.size())
{
getline(input, lines[i]);
}
else
{
lines.emplace_back();
getline(input, lines.back());
}
}
// process/print 'lines' here.
// Size is 'count'.
}
...

如何在vector::clear()上保留向量元素的容量?

我想不出一种简单明了的方式来实现这一点。

这是因为没有一种简单的方法可以实现你想要的。一旦你销毁了一个字符串,它的分配就没有了,而且没有保证的方法可以把它拿回来。

您可以做的是,在清除源向量之前,将字符串移动到另一个向量上。然后在清理之后,您可以在空闲时将琴弦移回。然而,尽管从技术上讲,这将满足标题中所述的要求,但我不认为这对您来说比一开始不清除矢量更有用。


我想你想";保持容量";以避免出于优化目的而进行不必要的分配。取决于什么";处理";这意味着,根本不将它们存储在矢量中,而是读取输入直到换行、处理/打印,然后读取下一行,依此类推,可能会更有效。这样,您只分配一次单个字符串(或随着行增长到最长的输入行而分配几次)。