jeudi 28 décembre 2017

Iterating through vector of vectors in C++

I am trying through vector of vectors (2D vector) in C++. I used method from this answer. Here is code.

#include <iostream>
#include<vector>

void printVec(std::vector<std::vector<double>> *v1)
{
    //displaying vector v1
    std::vector <std::vector<double> >::const_iterator row;
    std::vector<double>::const_iterator col;

    std::cout<<"Displaying vectors";

    for (row = v1->begin(), row != v1->end(); ++row) //error 
    {
        for (col = row->begin(); col != row->end(); ++col)
        {
            std::cout << *col << " ";
        }
        std::cout <<std::endl;
    }
}
int main()
{
    int nRowA, nColA;
    nRowA = 2;
    nColA = 4;

    std::vector< std::vector<double>> A, B, C;
    std::vector<double> temp1;

    //creating multidimensional vector A
    for (int i = 0; i < nRowA; ++i) 
    {
        for (int j = 0; j < nColA; ++j)
        {
            temp1.push_back(j+1);
        }
        A.push_back(temp1);
    }

    //Displaying vector A
    printVec(&A);
    return 0;
}

I am creating a vector in main() is passing it by pointer to printVec(). In printVec(), I am using iterators to iterate through this 2D pointer. But getting error at the row indicated in the code as //error. Can someone tell what is going wrong?

(I am aware about using range for loop and passing vector of vector as reference instead of as pointer. )

Aucun commentaire:

Enregistrer un commentaire