C++计数错误

Counting error in C++

本文关键字:错误 C++      更新时间:2023-10-16

我正在编写一个程序来输出矩阵的转置。当我在正方形或列多于行的矩阵上使用它时,该程序可以工作,但是当我尝试在行多于列的矩阵上使用它时,会给出错误的输出。

该程序的要点是它将数字读取到一个向量,然后将该向量推到2D向量data上。这部分代码工作正常(据我所知),我认为错误在这些循环中

if (data[0].size() < data.size()) // number of columns < number of rows BREAKS
{ // test52 gets here
for(size_t i=0; i<data[0].size(); ++i) // loops over the number of rows
{
  for(size_t j=0; j<data.size(); ++j) // loops over the number of columns (the number of entries in each row)
  {
    cout << data[j][i] << "t";
  }
  cout << endl;
}

}

如果我用矩阵运行这个

1,2
3,4
5,6
7,8
9,10

输出是1 3 5 7 9的,所以它错过了第二列。

我在编译和运行时没有收到任何错误。我已经盯着代码一个多小时了,在我的生活中,我无法弄清楚出了什么问题。

任何帮助将不胜感激。

编辑

对不起大家,该程序运行正常。问题是我试图让程序以错误的格式读取文本文件(我忘记了逗号)!

谢谢你的帮助。

替换

i<data[i].size();

i<data[0].size();

这个:

for(size_t i=0; i<=data[0].size(); ++i) // loops over the number of rows

应该是这样的:

for(size_t i=0; i<data[0].size(); ++i) // loops over the number of rows

您正在迭代向量的末尾并获得未定义的行为