当我清除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'.
}
...
答案 0 :(得分:0)
如何保留vector :: clear()上矢量元素的容量?
我想不出一种以直接,简单的方式实现这一目标的方法。
那是因为没有一种简单的方法来实现您想要的。一旦销毁了一个字符串,它的分配就消失了,没有保证的方法可以将其取回。
您可以做的是在清除源向量之前将字符串移动到另一个向量上。然后,在清除之后,您可以在闲暇时将琴弦移回原处。但是,尽管从技术上讲,这可以满足标题中所述的要求,但我不认为这比不清除向量会更有用。
我假设您要“保留容量”以避免出于优化目的而进行不必要的分配。根据行的“处理”的含义,根本不将它们存储在矢量中,而是读取输入直到换行,处理/打印,然后读取下一行,等等,可能会更有效率。这样,您只需分配一个字符串一次(或在该行增长到最长输入行时分配一次)。