1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
#include <vector>
#include <numeric>
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v);
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<T>>& v);
int main()
{
std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };
std::cout << "Display the 1D vector...\n";
std::cout << vec << '\n';
std::cout << "\nCreating the 2D vector...\nRows: ";
size_t row_size { };
std::cin >> row_size;
std::cout << "Columns: ";
size_t col_size { };
std::cin >> col_size;
std::cout << '\n';
// create a 2D vector with known sizes, all values initialized to zero
std::vector<std::vector<int>> matrix(row_size, std::vector<int>(col_size));
// initialize the vector with some values other than zero
int start { 101 };
int offset { 100 };
// step through each row and fill the row vector with some values
for (auto& itr : matrix)
{
std::iota(itr.begin(), itr.end(), start);
start += offset;
}
std::cout << "Display the 2D vector...\n";
std::cout << matrix;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
{
for (auto const& x : v)
{
os << x << ' ';
}
return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<T>>& v)
{
for (auto const& x : v)
{
os << x << '\n';
}
return os;
}
| |