【问题标题】:push_back struct into vectorpush_back 结构到向量中
【发布时间】:2016-04-26 11:59:43
【问题描述】:
 //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;

}

【问题讨论】:

标签: c++ vector push-back


【解决方案1】:

您正在使用未初始化的变量 undefined behavior

int i;

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

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

int i = 0;

你有另一个问题

mString[i] = '\0';

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

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

为空终止符留出空间。

【讨论】:

  • 这完全解决了它!谢谢!
【解决方案2】:

http://www.cplusplus.com/reference/vector/vector/push_back/

push_back 将值复制到向量。 MyString 类是否正确定义了复制 mString 成员的复制构造函数?我猜这可能是你的问题。

【讨论】:

  • 答案不应该是猜测。现在 OP 实际上已经提供了代码,您可以看到他们有一个复制构造函数,但它有 UB。
  • 抱歉 - 在提供完整代码之前发布了答案。
【解决方案3】:

我认为有两个错误,你已经完成了 1.for(i; i

【讨论】:

    【解决方案4】:

    复制构造函数的正确版本

    MyString(const MyString &copy)
    {
        mString = new char[copy.mLength + 1];
        int i = 0;
    
        for(; i < copy.mLength; i++)
        { mString[i] = copy.mString[i]; }
    
        mString[i] = '\0';
        mLength = copy.mLength;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-28
      • 2018-02-21
      • 1970-01-01
      • 2013-03-28
      • 2016-01-24
      • 2014-03-14
      • 1970-01-01
      • 2021-06-23
      • 2020-11-20
      相关资源
      最近更新 更多