我有一个矩阵类,将其数据存储在 std::vector
中:
std::vector<double> mData(mRows*mCols);
该类有一个从该矩阵中提取列的方法:
std::vector<double> matrix::getCol(const int &n) const
{
std::vector<double> Col(mRows);
for(int ii = 0; ii < mRows; ii++)
{
Col[ii] = mData[n*mRows + ii];
}
return Col;
}
我希望此方法返回对作为 mData
子集的 vector 的引用。这样的事情可能吗?
std::vector<double>& matrix::getCol(const int &n)
{
std::vector<double> Col(mRows);
&Col[0] = &mData[n*mRows];
return Col;
}
我对此感兴趣的原因是我想在赋值中使用此方法:
matrix A(rows,cols);
std::vector<double> newCol(rows);
A.getCol(0) = newCol;
最佳答案
另一种选择是编写一个 array_ref
类,其中包含指向数据和大小的指针,但不拥有该数据。它将允许修改元素,但不允许插入或删除。然后,您可以将其构造为指向常规数组、 vector 或两者的子集。对于具有 string_ref
类的字符串来说,这实际上是一种相当常见的做法,它可能引用 std::string
或 char*
的内容code> 或 char[N]
。这将相当简单,并且几乎不需要对现有的矩阵类进行任何更改。
//untested sample
template<class T>
struct array_ref {
typedef T value_type;
typedef T& reference;
typedef T* pointer;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef T* iterator;
typedef const T* const_iterator;
array_ref() : data(nullptr), len(0) {}
array_ref(T* data_, size_t len_) : ptr(data_), len(len_) {}
T& at(size_t index) {assert_range(index); return ptr[index];}
const T& at(size_t index) const {assert_range(index); return ptr[index];}
T* begin() {return ptr;}
const T* begin() const {return ptr;}
T* end() {return ptr+len;}
const T* end() const {return ptr+len;}
T* data() {return ptr;}
const T* data() const {return ptr;}
T& operator[](size_t index) {return ptr[index];}
const T& operator[](size_t index) const {return ptr[index];}
size_t size() const {return len;}
private:
void assert_range(size_t index) const
{if (index>=len) throw std::out_of_range("out of range");}
T* ptr;
size_t len;
};
关于c++ - 包含另一个 vector 的部分子集的 vector 都指向同一内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516140/