Reputation: 11
This might be easy but I just cant find a solution. I created a 2D vector like this:
vector<vector<int> > matrix;
vector<int> row;
for (int i = 0; i < x;i++) {
row.push_back(i);
}
for (int i = 0; i < x; i++) {
matrix.push_back(row);
}
The problem I have is that I now wanna add rows and columns as I need them because I might run out of matrix space over time but I don't know how to do it. The rows are easy I can just .push_back another row to the bottom end of the matrix...but I have no Idea how to add another column.
I'm sorry if this question is super stupid but I'm not that experienced in programming yet and I couldn't find anything on the particular problem of adding columns to a 2D vector.
Upvotes: 0
Views: 2496
Reputation: 1263
vector<vector<T>> is a BAD way to implement a matrix. Well - it may not be a bad backend implementation, but its a bad public API.
I'd suggest using some library designed to support a Matrix. A few come to mind:
https://github.com/SophistSolutions/Stroika/blob/V2.1-Release/Library/Sources/Stroika/Foundation/Math/LinearAlgebra/Matrix.h
https://docs.opencv.org/3.4/d3/d63/classcv_1_1Mat.html
http://arma.sourceforge.net/docs.html#part_classes
or write your own and implement the basic functions directly.
Upvotes: 1
Reputation: 13424
Here is a simple function that will add a column to your matrix at a specified position:
void add_column(std::vector<std::vector<int>>& matrix,
const std::vector<int>& column, std::size_t position)
{
if(matrix.size() < position || position < 0) return; // check for position correctness
std::size_t index = 0;
for(auto& row : matrix){
row.insert(row.begin() + position, column[index++]);
}
}
For example, given a matrix:
std::vector<std::vector<int>> matrix;
and initializing it like so:
std::vector<int> column;
for (int i = 0; i < 3; i++) {
column.push_back(3);
}
for (int i = 0; i < 3; i++) {
matrix.push_back(column);
}
you end with with 3x3 matrix of 3
s. Now, adding a column in between the first and the second one:
add_column(matrix, std::vector<int>({9, 9, 9}), 1);
and printing it:
for (auto& row : matrix) {
for (const auto x : row) {
std::cout << x << ' ';
}
std::cout << std::endl;
}
You end up with:
3 9 3 3
3 9 3 3
3 9 3 3
Upvotes: 0
Reputation: 56945
Adding to your code, the idea is to loop over each row in the matrix and push a new element onto each vector. Together, all of these elements are a new column.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Initialize a 3x3 matrix
vector<vector<int>> matrix;
vector<int> row;
int x = 3;
for (int i = 0; i < x; i++) {
row.push_back(i);
}
for (int i = 0; i < x; i++) {
matrix.push_back(row);
}
// Add a column; the matrix is now 3x4
int newElement = 3;
for (auto &row : matrix) {
row.push_back(newElement);
}
// Print the matrix
for (auto &row : matrix) {
for (auto &cell : row) {
cout << cell << ' ';
}
cout << endl;
}
return 0;
}
You'll likely want to separate this code into functions.
Upvotes: 2