gpt4 book ai didi

c++ - 关于c++中 vector 的地址

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:12 26 4
gpt4 key购买 nike

在 C++ 中

像我一样

        vector<vector<string> > input;
for(int i=0;i<=1000;i++){

vector<string> temp;
temp.pushback(everytime change the input value);
.
.
.just continues push some string in temp
.
.
temp.pushback(everytime change the input value);
input.pushback(temp);
}

我的问题是,如果我们将一些字符串放在临时文件中大约 1000 次,这些临时文件是否会共享地址?就像当 i=500 时,新的临时地址将使用我在 i=1 时创建的第一个临时地址的地址?或者虽然 vector(string) 使用与 temp 相同的名称,但地址总是不同的。

因为我想做一个二维动态数组之类的东西,所以我想

           vector<vector<string> > input;

,我需要的是每个字符串类型的 vector temp 应该安全地保持输入。除了

              vector<vector<string> > input;

最佳答案

您的代码正在泄漏;当你写的时候

vector<string> temp = *new vector<string>;

你正在分配一个空的 vector<string>在堆上,然后在 temp复制它.每次进行此循环时,都会泄漏一个 vector (一个空 vector ,因此可能只有几个字节)。

这个分配根本不需要,你可以这样写:

vector<string> temp;

此外,您正在创建一个临时 vector ,填充它并将其插入另一个 vector 。更好的方法可能是:

  input.resize(1 + input.size());       // make room for a new vector
vector<string>& temp = input.back(); // call it temp in the following
...
temp.push_back(...);

这样你就分配了已经在input中的新 vector 并直接向其中添加元素... temp就像新添加的 vector 的临时“昵称”一样。

关于c++ - 关于c++中 vector 的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16166560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com