如何在vector::clear()上保持向量元素的容量
How to preserve capacity of vector elements on vector::clear()?
清除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()上保留向量元素的容量?
我想不出一种简单明了的方式来实现这一点。
这是因为没有一种简单的方法可以实现你想要的。一旦你销毁了一个字符串,它的分配就没有了,而且没有保证的方法可以把它拿回来。
您可以做的是,在清除源向量之前,将字符串移动到另一个向量上。然后在清理之后,您可以在空闲时将琴弦移回。然而,尽管从技术上讲,这将满足标题中所述的要求,但我不认为这对您来说比一开始不清除矢量更有用。
我想你想";保持容量";以避免出于优化目的而进行不必要的分配。取决于什么";处理";这意味着,根本不将它们存储在矢量中,而是读取输入直到换行、处理/打印,然后读取下一行,依此类推,可能会更有效。这样,您只分配一次单个字符串(或随着行增长到最长的输入行而分配几次)。
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C