Я в основном реализую матрицу с помощью 2d-вектора. Создание и заполнение матрицы происходит гладко, однако, когда я хочу добавить 2 матрицы вместе, я получаю ошибку времени выполнения. Я уверен, что это имеет какое-то отношение к итераторам, которые не входят в for loop
Вероятно, есть больше ошибок, чем я подозреваю. Я размещаю весь источник ниже:
#include <iostream>
#include <vector>
using namespace std;
void fillMatrix(vector< vector<int> > &data1)
{
vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = data1.begin(); row != data1.end(); ++row) {
for (col = row->begin(); col != row->end(); ++col) {
cout << "please enter an integer:";
int tt1;
cin >> tt1;
*col = tt1;
}
}
}
void printMatrix(vector< vector<int> > &data1)
{
vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = data1.begin(); row != data1.end(); ++row) {
for (col = row->begin(); col != row->end(); ++col) {
cout << *col;
}
cout << endl;
}
}
int main()
{
//Create the matrices
vector< vector<int> > data1(2, vector<int>(2));
vector< vector<int> > data2(2, vector<int>(2));
//fill the matrices with numbers
fillMatrix(data1);
fillMatrix(data2);
//initialize the matrice iterators;
vector< vector<int> >::iterator row1;
vector<int>::iterator col1;
vector< vector<int> >::iterator row;
vector<int>::iterator col;
row1 = data2.begin();
col1 = row1->begin();
//go through the matrice and add everything
for (row = data1.begin(); row != data1.end(); ++row) {
for (col = row->begin(); col != row->end(); ++col) {
if(col1 != row1->end()){
*col1 = *col1 + *col;
++col1;
}
}
if(row1 != data2.end()){
++row1;
}
}
cout << "ENDL" <<endl;
printMatrix(data1);
cout << "ENDL" <<endl;
printMatrix(data2);
return 0;
}
В вашей функции main()
ваш итератор col1
должен быть инициализирован row1->begin()
.
//add the termination condition here for safety sake.
for (row = data1.begin(); row != data1.end() && row1 != data2.end(); ++row) {
//Add this.
col1 = row1->begin();
//add the termination condition here for safety sake.
for (col = row->begin(); col != row->end() && col1 != row1->end(); ++col) {
if(col1 != row1->end()){
*col1 = *col1 + *col;
++col1;
}
}
if(row1 != data2.end()){
++row1;
}
}