当尝试从一组列“向量”创建矩阵时,不相关的 std::vector 变得混乱。我创建了一个 std::vector 并将其初始化为大小 1,但不知怎的,它的大小变成了 0,而没有在任何代码中进行操作。我怀疑内存有问题,但我没有做过任何手动内存操作。
我已经删除了有问题的代码并将其发布在下面。
#include "GMatrix.h"
int main(int argc, char *argv[])
{
GVector<4> temp1{std::array<float,4>{0,0,0,0}};
GVector<4> temp2{std::array<float,4>{0,0,0,0}};
GVector<4> temp3{std::array<float,4>{0,0,0,0}};
GVector<4> temp4{std::array<float,4>{0,0,0,0}};
GVector<4> temp5{std::array<float,4>{0,0,0,0}};
std::array<GVector<4>,5> myArray{temp1,temp2,temp3,temp4,temp5};
//Weird behavior only happens if the number of vectors > dimension of the vectors
std::vector<int> problem(1); //Unused vector of size 1
printf("%d-",problem.size()); // prints 1-
GMatrix<4,myArray.size()> desiredMat{myArray};
printf("%d-",problem.size()); // prints 0- for some reason
printf("%d-",problem[0]); //Seg fault here since 'problem' has size 0
return 0;
}
G矩阵
#include <array>
#include <vector>
#include <stdexcept>
#include "GVector.h"
template <size_t R, size_t C>
class GMatrix
{
public:
std::array<float,R*C> data;
//0 Matrix
GMatrix() : data{}{}
GMatrix(std::array<float,R*C> matrixData){
data = matrixData;
}
//Forms a matrix from column vectors
GMatrix(std::array<GVector<R>,C> vectors) : data{}{
for (int i=0;i<C;i++) { //each vector
for (int crd=0;crd<R;crd++) { //each coordinate
this->data[i*C + crd] = vectors[i].data[crd];
}
}
}
};
G向量
#include <array>
#include <stdexcept>
template <size_t T>
class GVector
{
public:
std::array<float,T> data;
GVector() : data{}{}
GVector(std::array<float,T> given) {
this->data = given;
}
float& operator[](size_t index)
{
if(index>=T){
std::out_of_range e("Index out of range");
throw e;
}
return data[index];
}
};
代码应打印 1-1-0- 并正常终止。相反,它会在被段错误中断之前打印 1-0-。
我将“myArray”更改为具有不同数量的向量和不同的向量维度。这让我更加困惑,因为只有当向量量大于向量的维度时才会出现这个问题。 (std::array
此代码应该从 GVectors 'myArray' 列的集合生成 GMatrix 'desiredMat'。 'desiredMat' 没有问题,所有值都是正确的,但它的创建混淆了不相关的 std::vector '问题'。
你有一个算术错误导致越界写入
i*C + crd
应该是i*R + crd