由2d Vector实现的矩阵运行时错误

时间:2013-11-23 18:36:37

标签: c++

我基本上是通过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's 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;
}

1 个答案:

答案 0 :(得分: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;
         }
    }