I have a matrix A
and I need to pass a pointer to a function
to access the elements of a given column, here is a part of the code, where PtrColumn
should be a pointer to the vector representing the column j
of A
. Is there a way to get this pointer without calculating the transpose of the matrix A
.
vector<vector<double>> A;
int l=4,c=5;
A.reserve(l)
for(size_t i=0;i<l;++i)
{
vector<double> row;
row.reserve(c)
for(size_t j=0;j<c;++j)
row.puch_back(j);
A.puch_back(row);
}
////// some part of the code/////
for(size_t j=0;j<c;++j)
function(PtrColumn) //PtrColumn is a pointer to a vector, and my vector is the column j of A
I would use a matrix class and a wrapper class for the columns:
#include <iostream>
#include <vector>
class Matrix;
class Column {
Matrix *A;
std::size_t column;
public:
Column(Matrix &A, std::size_t column);
double &operator[](std::size_t row);
std::size_t size() const;
};
class Matrix {
std::size_t columns;
std::size_t rows;
std::vector<double> A;
public:
Matrix(std::size_t l, std::size_t r) : columns(r), rows(l), A(l * r) {}
double &operator()(std::size_t i, std::size_t j) { return A[i * columns + j]; }
std::size_t getColumns() const { return columns; }
std::size_t getRows() const { return rows; }
Column getColumn(std::size_t column) { return Column(*this, column); }
};
Column::Column(Matrix &A, std::size_t column) : A(&A), column(column) {}
double &Column::operator[](std::size_t row) { return (*A)(row, column); }
std::size_t Column::size() const { return A->getRows(); }
void function(Column col) {
std::cout << col[2] << '\n';
std::cout << col.size() << '\n';
}
int main() {
int l = 4, c = 5;
Matrix A(l, c);
for(size_t i=0;i<l;++i)
for(size_t j=0;j<c;++j)
A(i, j) = j;
////// some part of the code/////
for(size_t j = 0; j < c; ++j)
function(A.getColumn(j)); //PtrColumn is a pointer to a vector, and my vector is the column j of A
}
Here is a code without matrix class
#include <iostream>
#include <vector>
class Column {
std::vector<std::vector<double>> *A;
std::size_t column;
public:
Column(std::vector<std::vector<double>> &A, std::size_t column) : A(&A), column(column) {}
double &operator[](std::size_t row) { return (*A)[row][column]; }
std::size_t size() const { return A->size(); }
};
void function(Column col) {
std::cout << col[2] << '\n';
std::cout << col.size() << '\n';
}
int main() {
std::vector<std::vector<double>> A;
int l=4,c=5;
A.reserve(l);
for(size_t i=0;i<l;++i) {
std::vector<double> row;
row.reserve(c);
for(size_t j=0;j<c;++j)
row.push_back(j);
A.push_back(row);
}
////// some part of the code/////
for(size_t j=0;j<c;++j)
function(Column(A, j)); //PtrColumn is a pointer to a vector, and my vector is the column j of A
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.