我得到了一个“答案”;矢量下标超出范围“;错误 我正在编写一个程序,从TXT文件中读取一些数字,并用C++将它们保存到矩阵中。但我不太熟悉矩阵的概念,有点困惑。当我试着运行这个程序时,我得到了向量订阅超出范围的错误,我不知道如果有人看到我的代码并告诉我正确的方法,那该怎么办

我得到了一个“答案”;矢量下标超出范围“;错误 我正在编写一个程序,从TXT文件中读取一些数字,并用C++将它们保存到矩阵中。但我不太熟悉矩阵的概念,有点困惑。当我试着运行这个程序时,我得到了向量订阅超出范围的错误,我不知道如果有人看到我的代码并告诉我正确的方法,那该怎么办,c++,vector,matrix,assertion,C++,Vector,Matrix,Assertion,这是我的密码 #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include "strutils.h" #include <iomanip> using namespace std; void Print(const vector<vector<int>> &

这是我的密码

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include "strutils.h"
#include <iomanip>
using namespace std;

void Print(const vector<vector<int>> & mat)
{
for (int j=0; j < mat.size(); j++)
{   
    for (int k=0; k < mat[0].size(); k++)
    {   
        cout << mat[j][k];
    }
    cout << endl;
}
}


int main()
{
string filename;
int countRow = 0, countCol = 0, emptyCount = 0;
cout << "Please enter the input file name: ";
cin >> filename;

ifstream input;
input.open(filename);

while(input.fail())
{
    cout<< "Could not open the file please enter the correct file name:";
    cin >> filename ;
    input.open(filename);
}

while(!input.eof())
{
    string s;
    int num;
    while (getline(input, s))
    {
        countRow++;
        vector<vector<int>> mat(countRow, vector<int>(countCol));
        istringstream input(s);
        while (input >> num)
        {
            countCol++;
            emptyCount++;
            vector <int> row(countCol);
            mat.push_back(row);
            mat [(countRow - 1)] [(countCol - 1)] = num;
        }
        countCol = 0;

    }


}
vector<vector<int>> mat(countRow, vector<int>(emptyCount/countRow));
Print(mat);

cin.get();
cin.ignore();
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括“strutils.h”
#包括
使用名称空间std;
无效打印(常量向量和矩阵)
{
对于(int j=0;j>num)
{
countCol++;
emptyCount++;
向量行(countCol);
垫子向后推(世界其他地区);
mat[(countRow-1)][(countCol-1)]=num;
}
countCol=0;
}
}
向量矩阵(计数行,向量(空计数/计数行));
印刷品(mat);
cin.get();
cin.ignore();
返回0;
}

我不知道从哪里开始。您正在创建大量临时文件 向量,你从不使用;然后你输出一个向量 没有任何你读到的数据,你在计算 行和行,尽管向量本身会这样做 正如@Nick指出的,你有一个
mat[countRow]
-1][countCol-1]
其中
countCol
保证更大 比它所索引的向量还要多,这个有什么问题吗 以下内容适用于您的读取循环:

std::vector<std::vector<int>> mat;
std::string line;
while ( std::getline( input, line ) ) {
    mat.push_back( std::vector<int>() );
    std::istringstream input( line ):
    int num;
    while ( input >> num ) {
        mat.back().push_back( num );
    }
}
std::向量矩阵;
std::字符串行;
while(std::getline(输入,行)){
mat.push_back(std::vector());
std::istringstream输入(行):
int-num;
while(输入>>num){
mat.back().推回(num);
}
}
std::vector
跟踪大小。不要创建新的 每次在内部循环中使用向量。并且只创建一个嵌套的
在第二个for循环中,您应该对照mat[j]进行检查,而不总是第一个元素

for (int k=0; k < mat[j].size(); k++)
for(int k=0;k
你不能依赖于
mat[0]
的大小来计算其他向量的大小。它们可能更小/更大。@Nick从
mat
的构造来看,这似乎不是问题。但总体来说,这仍然是一个很好的建议。您是否已经调试了程序以查看错误发生的位置?请先这样做,然后再让这里的人为您这样做为什么输入上的外循环?为什么循环中构造的所有向量都不会超过循环。