gpt4 book ai didi

c++ - 结构中的 vector - 最佳方法? C++

转载 作者:可可西里 更新时间:2023-11-01 16:36:34 25 4
gpt4 key购买 nike

我想在我的结构中包含一个 vector 。

这是我的结构:

struct Region 
{
bool hasPoly;
long size1;
long size2;
long size3;
long size4;
long size5;
long size6;
//Mesh* meshRef; // the mesh with the polygons for this region
long meshRef;
std::vector<int> PVS;
} typedef Region;

此声明中的 vector 是否有效,或者做一个指向 vector 的指针是否更有意义。在指向 vector 的指针的情况下,我是否需要分配一个新的 vector 。我将如何做到这一点?

谢谢!

编辑:问题是它最终会导致指向 xmemory.h 的错误,这是一个包含在 MSVC++ 平台中的文件。

    void construct(pointer _Ptr, _Ty&& _Val)
{ // construct object at _Ptr with value _Val
::new ((void _FARQ *)_Ptr) _Ty(_STD forward<_Ty>(_Val)); // this is the line
}

有趣的是,如果我在结构之外分配它并且只是在我使用的函数中分配它就不会发生。有什么想法吗?

最佳答案

不用typedef也可以这样写:

struct Region 
{
bool hasPoly;
long size1;
long size2;
long size3;
long size4;
long size5;
long size6;
long meshRef;
std::vector<int> PVS;
}; // no typedef required

回答您的问题:

Is the vector in this declaration valid

是的,是的。

or would it make more sense to do a pointer to a vector.

不,可能不是。如果这样做,则必须为复制行为实现复制构造函数、赋值运算符和析构函数。您最终会得到相同的结果,但这将是额外的工作并且可能会引入错误。

In the case of a pointer to a vector, do I need to allocate a new vector. How would I accomplish this?

您需要实现复制构造函数复制赋值运算符析构函数:

// Copy constructor
Region(const Region & rhs) :
hasPoly(rhs.hasPoly),
// ... copy other members just like hasPoly above, except for PVS below:
PVS(new std::vector<int>(*rhs.PVS))
{
}

// Copy assignment operator
Region & operator=(const Region & rhs)
{
if (this != &rhs)
{
hasPoly = rhs.hasPoly;
// ... copy all fields like hasPoly above, except for PVS below:

delete PVS;
PVS = new std::vector<int>(*rhs.PVS);
}
return *this;
}

// Destructor
Region::~Region()
{
delete PVS;
}

底线:您的代码没有问题。您不需要更改它。

编辑:修复赋值运算符:检查与 this 的比较并返回 *this。

关于c++ - 结构中的 vector - 最佳方法? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6246793/

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