gpt4 book ai didi

c++ - push_back 结构到 vector 中

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:03 24 4
gpt4 key购买 nike

 //prototype    
void Split(char c, vector <MyString> &outputVector) const

//partial code inside split function
// create new MyString object to push into output vector
MyString substr;
substr.mString = newString;
substr.mLength = size;

// push new item
outputVector.push_back(substr);

在我越过 outputVector.push_back() 行后,mString 数据成员未保留。

//I have two constructors
MyString()
{
mString = NULL;
mLength = 0;
}

/*************************************************
* MyList copy constructor
* creates a deep copy of a MyString item
************************************************/
MyString(const MyString &copy)
{
mString = new char[copy.mLength];
int i;

for(; i < copy.mLength; i++)
{ mString[i] = copy.mString[i]; }

mString[i] = '\0';
mLength = copy.mLength;

}

enter image description here

最佳答案

您正在使用一个未初始化的变量,它是 undefined behavior

int i;

for(; i < copy.mLength; i++)

这里我们不知道 i 是什么,所以任何事情都可能发生,但很可能 icopy.mLength 大,所以我们永远不要进入 for 循环。为了获得正确的行为,将 i 设置为 0,如

int i = 0;

您还有其他问题

mString[i] = '\0';

当我们到达 i == copy.mLength 行时,但数组只有 copy.mLength 的大小,所以我们已经结束了,因为数组是基于 0 索引的。您很可能需要将分配更改为

mString = new char[copy.mLength + 1]; 

为空终止符留出空间。

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

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