C ++中使用邻接矩阵和列表的图形

时间:2018-12-05 02:14:54

标签: c++ graph linked-list

我目前正在使用Graph进行小型作业,以在邻接表中显示字符。通常情况下,我们的教授会向我们提供他所研究的课堂实例,但是这次他没有给我们任何实例。这只是一个额外的学分分配,但我寻求帮助的真正原因是,我们周五的课堂分配有50分。我和我的其他同学都知道当前的情况。这是我无法获得的功能。

我的主要问题是如何转换字符串*返回的值。 要在调用markEdge函数时使用split函数?

void loadListFromFile(Graph& g, string filename) {
     /* TODO (1):
     *
     * Open the file and update the matrix with the proper
     * edge status, i.e. 1 if there is an edge from source
     * to target.
     * 
     * The file format is:
     * 
     * sourceNode adjacentNode1 adjacentNode2 ...adjacentNode3
     * 
     * Each node is a single character in the range A-Z.
     */

    ifstream ifs;
    ifs.open(filename);

    if (ifs.is_open() ==  false){
        cerr << "Error opening file for reading." << endl;
    }

    string line;
    int tokenCount;

    getline( ifs, line);

    while (!ifs.eof()){

        split(line, ' ', tokenCount);

        getline(ifs, line);
    }

}// end loadListFromFile()

这是给定的用于分割值的函数

//given
string * split(const string& str, const char delimiter, int& tokenCount){
string * fields = nullptr;
tokenCount = 0;

string token;
string remaining = str;
if (remaining.back() == '\n') {
    remaining.pop_back();
}
remaining.push_back(delimiter);

size_t delimiterPos = remaining.find_first_of(delimiter, 0);
while ( delimiterPos != string::npos ) {
    token = remaining.substr(0, delimiterPos);
    remaining = remaining.substr(delimiterPos + 1);

    if ( fields ) {
        // resize array and add new token.
        string * fieldsTmp = new string [tokenCount + 1];

        for (int i = 0; i <= tokenCount - 1; i++) {
            fieldsTmp[i] = fields[i];
        }
        fieldsTmp[tokenCount++] = token;

        delete [] fields;
        fields = fieldsTmp;
        fieldsTmp = nullptr;

    } else {
        // create array and add first token.
        fields = new string[tokenCount + 1];
        fields[tokenCount++] = token;
    }
    delimiterPos = remaining.find_first_of(delimiter, 0);
}
return fields;
}// end split()

这是我认为是正确的功能。

void markEdge(const int fromIndex, const char node) {
    /* TODO (1):
     * Add the node to the list at index fromIndex.
     */

    adjList->pushAt(fromIndex, node);

} //结束markEdge()

感谢您的帮助。

0 个答案:

没有答案