我使用下面的代码将多个.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 ++的运行时中实现?

最佳答案

如果要进一步使用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矢量的函数,然后可以对其进行处理。

07-24 09:45
查看更多