gpt4 book ai didi

c++ - 使用指向 vector 的指针,其中涉及使用 'new'

转载 作者:行者123 更新时间:2023-11-30 01:45:27 30 4
gpt4 key购买 nike

我想创建一个指向结构的指针 vector

vector<myStruct*> vec

对于 vector 中的元素,并非所有元素都包含数据。其中一些可能指向 NULL。那么,我是否应该首先在每个元素中通过 new 创建空间

for(int i = 0; vec.size() ;i++){
if (thisSpaceIsValid(i))
vec.at(i) = new myStruct;
else
vect.at(i) = NULL;
}

问题来了:
- 如果我对每个元素都使用 new,那会很慢。我怎样才能加快一点?有没有一种方法可以创建我需要的所有空间,自动将此类空间的指针访问到 vector (此处为vec)?

-如果以后我使用delete来释放内存,速度的问题还会困扰我吗?

最佳答案

If I use "new" for each element, it would be very slow. How can I speed it up a bit? Is there a way the create all the spaces that I need , that automatically access the pointer of such space to the vector("vec" here)?

你可以做到这一点。

假设您的 vector 的大小是 M 并且您只需要这些元素中的 N 来拥有指向对象的指针,而其他元素是空指针。您可以使用:

myStruct* objects = new myStruct[N];

然后,使用:

for(int i = 0, j = 0; vec.size(); i++)
{
if (thisSpaceIsValid(i))
{
if ( j == N )
{
// Error. Do something.
}
else
{
vec[i] = objects+j;
++j;
}
}
else
{
vect[i] = NULL;
}
}

您现在必须确保您能够跟踪objects 的值,以便您可以安全地使用

释放内存
delete [] objects;

附言

您的问题可能有更好、更优雅的解决方案。花更多时间考虑一下是值得的。

关于c++ - 使用指向 vector 的指针,其中涉及使用 'new',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34638556/

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