Example #1
0
void str2node2 (const std::string& str, nodes_t& node)
{
    //assert the node-id of a new node's parent is less than it
    std::vector < std::string > tokens;
    tokenize<std::string>(str, std::back_inserter(tokens));
    unsigned int len = tokens.size() / 2;
    node.resize (len);
    std::vector <int> sibling (len);
    for (unsigned int i=0; i<len; ++i){
        node[i].val = SingleString::get()->getPointer(tokens[2*i]);
        node[i].sibling = -1;
        node[i].child = -1;
        const int parent = atoi(tokens[2*i + 1].c_str()) -1;
        node[i].parent = parent;
        sibling[i] = -1;
        const unsigned int here = i;
        if (parent!=-1){
            if (node[parent].child == -1) node[parent].child = here;
            if (sibling[parent] != -1) node[sibling[parent]].sibling = here;
            sibling[parent] = here;
        };
    };
}
Example #2
0
void str2node (const std::string& str, nodes_t& node)
{
    try {
            unsigned int len = str.size();
            unsigned int size = 0;
            std::string buf = "";
            std::vector <std::string> tmp;

            for (unsigned int i = 0; i < len; i++) {
                if (str[i] == '(' || str[i] == ')') {
                if (! buf.empty()) {
                tmp.push_back (buf);
                buf = "";
                ++size;
                }
                if (str[i] == ')') tmp.push_back (")");
                } else if (str[i] == '\t' || str[i] == ' ') { 	  // do nothing
                } else {
                buf += str[i];
                }
            }

        if (! buf.empty()) throw 2;

        node.resize (size);
        std::vector <int> sibling (size);
        for (unsigned int i = 0; i < size; ++i) {
            node[i].parent = -1;
            node[i].child = -1;
            node[i].sibling = -1;
            sibling[i] = -1;
        }

        std::vector <int> sr;
        unsigned int id = 0;
        int top = 0;

        for (unsigned int i = 0; i < tmp.size(); ++i) {
            if (tmp[i] == ")") {
                top = sr.size()-1;
                if (top < 1) continue;
                unsigned int child  = sr[top];
                unsigned int parent = sr[top-1];
                node[child].parent = parent;
                if (node[parent].child == -1) node[parent].child = child;
                if (sibling[parent] != -1) node[sibling[parent]].sibling = child;
                sibling[parent] = child;
                sr.resize (top);
            } else {
                node[id].val = SingleString::get()->getPointer(tmp[i]);
                sr.push_back (id);
                id++;
            }
        }
        return;
    }
    catch (const int) {
        std::cerr << "Fatal: parse error << [" << str << "]\n";
        std::exit (-1);
    }
}