读取 2D 矢量

Reading into a 2D vector

本文关键字:矢量 2D 读取      更新时间:2023-10-16

>我从文件读取到 2D 矢量时遇到问题。我是 c++ 的新手,我没有看到我的代码有问题。

该文件遵循此模式。

5
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
0 0 1 0 0
...

我的算法来阅读它...

void Similarity::readData(Scanner& inStream){
        dataLength = inStream.nextInt();
        while(inStream.hasNext()){
                vector<int> temp;
                int tempInt = 0;
                for(int i = 0; i < dataLength; ++i){
                        tempInt = inStream.nextInt();
                        temp.push_back(tempInt);
                        temp.clear();
                }
                theData.push_back(temp);
                theData.clear();
        }
}

我的算法来打印它。

string Similarity::toString(){
        string result = "";
        for(int i = 0; i < theData.size(); ++i){
                for(int j = 0; j < dataLength; ++j){
                        result += convertInt(theData[i][j]);
                }
                result += "n";
        }
        return result;
}
string Similarity::convertInt(int number){
        stringstream s;
        s << number;
        return s.str();
}

toString 没有输出,是我需要处理的 readData 还是 toString?

谢谢。

这部分代码毫无意义(至少从流中消耗数字):

                    tempInt = inStream.nextInt();
                    temp.push_back(tempInt);
                    temp.clear();

因为temp.clear()会立即删除用 push_back() 插入的对象。

这同样适用于

            theData.push_back(temp);
            theData.clear();

我认为你确实需要一个temp.clear(),你现在有theData.clear()