gpt4 book ai didi

c++ - 在 vector 上调用 push_back 时出现段错误

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

我正在尝试为简单的整数行创建一个对象树结构。这是我的测试用例:

#include <vector>
#include <queue>
#include <iostream>

using std::vector;
using std::queue;
using std::cout;
using std::endl;

struct Node
{
Node(int r, int i)
: id(i)
, row(r)
{}

explicit Node(int i)
: id(i)
, row(0)
{}

Node()
: id(0)
, row(0)
{}

int nextLayer(queue<int>& queue, int& curRow)
{
int nextId = queue.front();
queue.pop();

for (int i = 0; i < children.size(); i++) {
if (children[i].id == nextId) {
if (children[i].row == 0)
return children[i].nextLayer(queue, curRow);
else
return children[i].row - 1;
}
}

if (queue.size() == 0) {
curRow++;
children.push_back(Node(curRow, nextId));
return curRow - 1;
}
else {
children.push_back(Node(nextId));
return children.end()->nextLayer(queue, curRow);
}
}

int id;
int row;
vector<Node> children;
};

int main()
{
queue<int> test;
int row = 0;
test.push(1);
test.push(2);
test.push(3);

Node testNode;
cout << testNode.nextLayer(test, row) << endl;
}

( live demo )

g++ -std=c++03 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In member function 'int Node::nextLayer(std::queue<int>&, int&)':
main.cpp:32:27: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i = 0; i < children.size(); i++) {
^
bash: line 8: 15216 Segmentation fault (core dumped) ./a.out

当我创建一个包含一些整数的队列并调用 nextLayer 时在上面,它给了我一个段错误。进一步调查,似乎子节点有一个 vector<Node>大于 0 的大小。

为什么会这样?

最佳答案

问题出在线路上

return children.end()->nextLayer(queue, curRow);

您取消引用 end() 而您不应该这样做。对于非空 vector ,正确的行是

return children.back().nextLayer(queue, curRow);

关于c++ - 在 vector 上调用 push_back 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25385206/

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