帮助构造函数(将_back元素放入指向数组的指针中)

发布于 2024-10-25 23:18:50 字数 451 浏览 10 评论 0原文

我在将元素插入指向我在代码中定义的某些元素(在本例中为食谱)的向量的指针时遇到问题。在代码的其他部分中,使用 Push_back 似乎工作正常,但如果我在此代码中使用它:

{
    Recipe defaultRec;
    this->recipes_ = new vector<Recipe>;
    this->recipes_->push_back(defaultRec);
}

我收到以下错误消息:

“Assignment 2.exe 中 0x01164031 处未处理的异常:0xC0000005:访问冲突读取位置 0xccccccce0”

Recipes_的声明是:

vector<Recipe>* recipes_;

希望任何人都可以帮助我,提前致谢。

I have a problem inserting elements into a pointer to a vector of some elements I defined in my code (in this case Recipes). In some other parts of the code, using push_back seems to work fine, but if I use it in this code:

{
    Recipe defaultRec;
    this->recipes_ = new vector<Recipe>;
    this->recipes_->push_back(defaultRec);
}

I get the following error message:

"Unhandled exception at 0x01164031 in Assignment 2.exe: 0xC0000005: Access violation reading location 0xcccccce0"

The declaration of recipes_ is:

vector<Recipe>* recipes_;

Hope anyone can help me, thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

意犹 2024-11-01 23:18:50

你的代码对我来说看起来不错。我确信问题出在其他地方。

顺便问一下,为什么使用指向向量的指针?为什么不这样做:

vector<Recipe> recipes_; //member

Recipe defaultRec;
recipes_.push_back(defaultRec);

至少这可以让您免于分配和释放。此外,很可能,指向向量的指针并不比上面的更好!

Your code looks fine to me. I'm sure the problem is somewhere else.

By the way, why do you use pointer to vector? Why not this:

vector<Recipe> recipes_; //member

Recipe defaultRec;
recipes_.push_back(defaultRec);

Atleast this saves you from allocation and deallocation. Besides, most likely, pointer to vector doesn't serve you any better than the above!

她比我温柔 2024-11-01 23:18:50

你的代码没有任何问题。问题可能出在其他地方。此类问题通常是由内存过度写入引起的,例如写入超出数组末尾或写入未初始化的内存位置。

There is nothing wrong with your code. The problem likely lies elsewhere. Problems like this are often caused by memory over writing such as writing past the end of an array or writing to an uninitialised memory location.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文