标记化:在读取多个.dat文件后引用特定标记

时间:2013-06-09 12:42:00

标签: c++

我使用下面的代码将多个.dat文件读入2D矢量并打印出令牌值。但是,我需要知道编译完成后是否所有标记值都将存储在内存中,我如何引用某个元素如token[3][27]作为进一步处理的示例:

for (int i = 0; i < files.size(); ++i) {
        cout << "file name: " << files[i] << endl;

        fin.open(files[i].c_str());
        if (!fin.is_open()) {
            cout<<"error"<<endl;
        }


        std::vector<vector<string>> tokens;

        int current_line = 0;
        std::string line;
        while (std::getline(fin, line))
        {

            cout<<"line number: "<<current_line<<endl;
            // Create an empty vector for this line
            tokens.push_back(vector<string>());

            //copy line into is 
            std::istringstream is(line);
            std::string token;
            int n = 0;

            //parsing
            while (getline(is, token, DELIMITER))
            {
                tokens[current_line].push_back(token);
                cout<<"token["<<current_line<<"]["<<n<<"] = " << token <<endl; 
                n++;
            }
            cout<<"\n";
            current_line++;
        }
        fin.clear();
        fin.close();

    }

我是否需要为每个文件创建2D矢量?可以在C ++运行时实现吗?

1 个答案:

答案 0 :(得分:1)

如果您想进一步使用2D矢量,则需要在for循环之外声明它。你这样做的方法是创建一个局部变量,每次循环迭代都会销毁它。

for (int i = 0; i < files.size(); ++i) {
    std::vector<vector<string>> tokens(i);
}
tokens[0][0]; // you can't do it here: variable tokens not declared in this scope

当然,你可以在while循环之后立即使用你的tokens容器,按照你提到的方式解决某些令牌。

要在for循环外部使用标记,您可以制作一个包含文件,线条,标记的3D矢量,或者将其作为返回某个文件的2D矢量的函数,然后就可以处理它。

相关问题