[CSI] vectors of vectors and iterators

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Dec 8 15:13:47 EST 2020


CSI students,

This it regarding todays lecture. I do not know what I did wrong
during the lecture, but the code that we built works as expected. The
below code assigns proper values and prints them out

--------------------------
#include <iostream>
#include <vector>

using std::cout; using std::endl;
using std::vector;

void fillingArray(vector<vector<int>>&);

int main() {
    vector<vector<int>> m;
    vector<int> row(4);
    for (int i = 0; i < 3; ++i)
        m.push_back(row);
    fillingArray(m);

    for (int i = 0; i < m.size(); ++i)
        for (int j = 0; j < m[i].size(); ++j)
            cout << m[i][j] << endl;
}

void fillingArray(vector<vector<int>>& x) {
    for (auto p = x.begin(); p < x.end(); ++p)
        for (auto q = p->begin(); q < p->end(); ++q)
            *q = (p - x.begin()) * (q - p->begin());
}
---------------------

Also, other than pushing back a separate vector or initializing a
vector of vector with a number of curly brackets at declaration, there
are two ways to allocate a vector of vector of specified size:

 vector<vector<int>> m(4);
 for (int i = 0; i < 4; ++i)
       m[i].resize(3);

Or even shorter:

 vector<vector<int>> m(4, vector<int>(3));

The second version invokes a constructor which initializes every vector
(of vectors) m to the particular vector of size 3.


Thanks,
--
Mikhail


More information about the cs13001 mailing list