Vector of vectors is an analog of 2d array. There is no standard method to serialize vector, a nested loop will do.
#include<iostream>
#include<vector>
#include<string>
#include <algorithm>
using std::for_each;
using std::cout;
using std::vector;
using std::endl;
class A {
public:
vector<int> getVector(int s) {
vector <int> A(s);
for (int j = 0; j < s; j++) {
A.push_back(j);
}
return A;
}
};
int main() {
A obj;
int n = 5;
vector<vector<int>> A;
A.push_back(obj.getVector(n)); // pushes a vector on vector A
A.push_back(obj.getVector(n - 1));
// classic for loop
for (auto itV = A.begin(), itVE = A.end(); itV != itVE; itV++)
{
for (auto itI = itV->begin(), itIE = itV->end(); itI != itIE; itI++)
{
cout << *itI;
}
}
cout << endl;
// much simpler range-based loop
for (auto& rowV : A ) // note that this a reference
// - no copy of stored vector is made.
for (auto el : rowV)
cout << el;
cout << endl;
// a generic lambda to serialize vector
auto print_vector = [](const auto& v) {
std::for_each(v.begin(), v.end(), [](auto const& it) {
std::cout << it << std::endl;
});
};
std::for_each(A.begin(), A.end(), print_vector );
return 0;
}
There are several ways to do that: use classic for() which is quite mouthful but allows fie control over some aspects, a range-based for loop is the shortest and most concise variant. THird approach is use of idiomatic function from standard library like for_each
, which would require creation of callable, which can be preferred if callable can be re-used of be swapped with something else, allowing some flexibility.