【发布时间】:2018-12-29 04:45:51
【问题描述】:
当我清除 vector<string> 时,vector 的容量会被保留,但向量中单个 strings 的容量不会被保留。有没有办法做到这一点?
我想不出一种直接、简单的方式来实现这一目标。这是一些测试代码,演示了我正在尝试做的事情:
#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'.
}
...
【问题讨论】:
-
为什么这对你很重要?
-
当你清除一个向量时,向量中没有字符串,所以说保留不存在的单个字符串的容量是没有意义的。
-
字符串的析构函数不是这样做的,这就是它没有意义的原因。您可以做的是管理自己的缓冲区并使用 string_view 查看缓冲区的后备存储。
-
您无法保留不再存在的东西。
clear()删除向量中的所有值。那些字符串不再存在。他们不再是了。他们不再存在。他们去见他们的创造者了。他们渴望峡湾。他们是前弦。它们不再存在,因此无法保存任何东西。 -
为了让这个“好”,我认为您将不得不将您当前的解决方案封装在一个新的
class中以隐藏丑陋的东西。