C++计数错误
Counting error in C++
我正在编写一个程序来输出矩阵的转置。当我在正方形或列多于行的矩阵上使用它时,该程序可以工作,但是当我尝试在行多于列的矩阵上使用它时,会给出错误的输出。
该程序的要点是它将数字读取到一个向量,然后将该向量推到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
您正在迭代向量的末尾并获得未定义的行为。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'