Q:

Segmentation Fault on calling push_back on a vector

I'm trying to create a tree structure of objects for simple rows of integers. Here's my testcase:
#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

When I create a queue with some integers and call nextLayer on it, it gives me a segmentation fault. Investigating further, it seems that child Nodes have a vector<Node> of size larger than 0.
Why does this happen?

A:

The problem is in the line
return children.end()->nextLayer(queue, curRow);

you dereference end() and you should not. For non-empty vector the correct line is
return children.back().nextLayer(queue, curRow);

A:

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

end() refers to the position after the last element, not to a valid element; you can't dereference that iterator. You presumably want to access the last element:
return children.back().nextLayer(queue, curRow);

