C++ 调用向量上的push_时出现分段错误
我正在尝试为简单的整数行创建对象的树结构。下面是我的测试用例:C++ 调用向量上的push_时出现分段错误,c++,C++,我正在尝试为简单的整数行创建对象的树结构。下面是我的测试用例: #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) {}
#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;
}
#包括
#包括
#包括
使用std::vector;
使用std::queue;
使用std::cout;
使用std::endl;
结构体类型
{
节点(int r,int i)
:id(i)
,第(r)行
{}
显式节点(int i)
:id(i)
,第(0)行
{}
节点()
:id(0)
,第(0)行
{}
int nextLayer(队列和队列,int和curRow)
{
int nextId=queue.front();
queue.pop();
对于(int i=0;inextLayer(queue,curRow);
}
}
int-id;
int行;
媒介儿童;
};
int main()
{
队列测试;
int行=0;
试验。推(1);
试验。推(2);
试验。推(3);
节点testNode;
问题就在眼前
return children.end()->nextLayer(queue, curRow);
您取消引用了end()
,不应该这样做。对于非空向量,正确的行是
return children.back().nextLayer(queue, curRow);
一个问题是
return children.end()->nextLayer(queue, curRow);
end()
指的是最后一个元素之后的位置,而不是有效元素;您不能取消对该迭代器的引用。您可能希望访问最后一个元素:
return children.back().nextLayer(queue, curRow);
我已经对你的问题进行了测试。请以后自己做。这应该是你的早期调试步骤,尽管在本例中你非常接近。这解决了问题,但我不明白为什么。我想end()
只给我一个迭代器,我可以用它访问最后一个元素。你能解释一下吗?另外,返回children.rbegin()->nextLayer(queue,curRow)
给你最后一个元素之后的一个元素的迭代器。rbegin()
给你最后一个元素的迭代器。@RobVerheyen:end()
在最后一个元素之后提供一个迭代器,这样(例如)您可以在它!=sequence.end()
时循环以覆盖整个序列。@RobVerheyen:v.begin()和v.end()
生成一个开放范围。也就是说,容器从v.begin()
到v.end()
独家。事实上,迈克在回答中解释了这一点。
return children.back().nextLayer(queue, curRow);