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

标签 c++ vector

当我清除 vector<string> , vector的容量被保留,但是个人的容量string vector 中的 s 不被保留。有办法实现吗?

我想不出一种直接、简单的方式来实现这一点。这是一些测试代码,演示了我正在尝试做的事情:

#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 中字符串的容量。然而,这是非常难看的。我正在寻找一个干净的解决方案。

    ...
    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'.
    }
    ...

最佳答案

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

I can't think of a way to achieve this in a straightforward, simple manner.

那是因为没有一种直接的方法可以实现您想要的。一旦你销毁了一个字符串,它的分配就消失了,并且没有保证的方法可以取回它。

您可以做的是在清除源 vector 之前将字符串移动到另一个 vector 上。清除后,您可以随意将琴弦移回原位。然而,虽然这在技术上可以满足标题中所述的要求,但我看不出这比不首先清除 vector 对您更有用。


我假设您想“保留容量”以避免为优化目的进行不必要的分配。根据行的“处理”含义,根本不将它们存储在 vector 中可能更有效,而是读取输入直到换行,处理/打印,然后读取下一行等等。这样一来,您只需分配一个字符串一次(或几次,因为该行会增长到最长的输入行)。

关于c++ - 如何在 vector::clear() 上保留 vector 元素的容量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966769/

相关文章:

c++ - 在类函数中初始化字符串数组

c++ - 关于STL中Vector的一些问题

c++ - 一个简单的 C++ 程序崩溃了吗?

c++ - 将不同类型的参数传递给函数模板

c++ - 有没有办法将 std::vector<const T*> 转换为 std::vector<T*> 而无需额外分配?

c++ - 如何在不使用C++函数的情况下显示链表中的元素?

r - 求两个向量的平均最大配对

c++ - 给定迭代器列表,如何从 vector 中删除元素?

android - 使用 OpenCV4Android (java API) 保存 ORB 特征向量

C++ 程序在创建 2000 个对象后崩溃