我有一个名为node的类。
// Code
void
parser::parse_line(string line) {
// Vector to hold the components of a line
// It is just like an array
vector<string> components;
// Split on space and add to vector
istringstream ssin(line);
while (getline(ssin, line, ' ')) {
components.push_back(line);
}
// Parse accordingly
// If driver
if (components.at(0).compare(driver) == 0) {
Node* source_node = new Node(components);
nodes.insert(pair<int, Node*>(source_node->get_id(), source_node));
} else if (components.at(0).compare(candidate) == 0) { // If candidate
Node *candidate_node = new Node(components);
nodes.insert(pair<int, Node*>(candidate_node->get_id(), candidate_node));
} else if (components.at(0).compare(sink) == 0) { // If sink
Sink_Node *sink_node = new Sink_Node(components);
nodes.insert(pair<int, Node*>(sink_node->get_id(), sink_node));
} else if (components.at(0).compare(edge) == 0) { // If edge
int parent_id = atoi(components.at(1).c_str());
int child_id = atoi(components.at(2).c_str());
Node *parent_node = nodes.find(parent_id)->second;
Node *child_node = nodes.find(child_id)->second;
parent_node->add_child_node(&child_node);
}
}
class Node
{
protected:
int id;
double x_coordinate;
double y_coordinate;
public:
// Constructor
Node();
Node(vector<string>& components) :
id(atoi(components.at(1).c_str())), x_coordinate(atof(components.at(2).c_str())), y_coordinate(atof(components.at(3).c_str())) {}
// Getters
inline int get_id() {return id;}
inline double get_x_coordinate() {return x_coordinate;}
inline double get_y_coordinate() {return y_coordinate;}
// Vector of child nodes
vector<Node*> child_nodes;
inline void add_child_node(Node* child_node)
{
child_nodes.push_back(child_node); }
};
}
如果我将外部向量初始化为成员,当我尝试push_back
子节点时,我会出现分段错误。
当我初始化函数内部的向量时,它可以工作,但不会产生我需要的结果。