vector元素被覆盖
std::vector elements are overwritten
我有一个函数ReadMatFromTxt
,它从文本文件中读取一些数字并将它们存储在vector<Mat>
中。该函数跳过一些包含标题的行,并将两个标题行之间的值作为Mat
保存到向量M_vec
中。当遇到标题行时,在Mat M
中累积的值将被添加到向量M_vec
中。
vector<Mat> ReadMatFromTxt(string filename, int rows, int cols)
{
double m;
Mat M = Mat::zeros(rows/2, cols, CV_32FC2); //Matrix to store values
vector<Mat> M_vec;
ifstream in(filename.c_str());
int lineNo = 0;
int cnt = 0; //index starts from 0
string line;
while(getline(in, line))
{
istringstream iss(line);
if(((lineNo % (rows+1)) == 0) && lineNo != 0)
// header found, add Mat to vector<Mat>
{
cout << M << endl;
M_vec.push_back(M);
cnt = 0;
lineNo++;
}
else
{
while (iss >> m)
{
int temprow = cnt / cols;
int tempcol = cnt % cols;
if(cnt < (rows*cols)/2) {
M.at<Vec2f>(temprow, tempcol)[0] = m;
} else {
M.at<Vec2f>(temprow - rows/2 , tempcol)[1] = m;
}
cnt++;
}
lineNo++;
}
}
return M_vec;
}
然而,当我在main中使用这个函数时,我看到vector的所有元素都是相同的(尽管文本文件包含不同的值)。
vector<Mat> M_vec;
M_vec = ReadMatFromTxt(txt_path.string(), rows, cols);
for(int i=0; i<M_vec.size(); i++)
{
cout << "M_vec[" << i << "] = " << M_vec[i] << endl;
}
在做push_back
将Mat
添加到向量时,我做错了什么吗?为什么要这样写?
opencv类Mat
赋值操作符和复制构造函数只修改引用计数器。Mat::zeros(rows/2, cols, CV_32FC2)
创建的深度数据保持不变。
使用
拥有多个数据实例M_vec.push_back(M.clone());
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 当将多个TypedArrayContents数组加载到V8数组中时(数组数组)时,最后一个元素将覆盖所有元素
- 覆盖数组元素时如何调用构造函数
- 在阵列中没有覆盖元素
- c ++ 我的 char* 数组被最后一个添加的元素覆盖
- 使用 char **,其中新元素覆盖以前的元素
- 尝试在文本文件中添加结构元素而不覆盖它
- 如何覆盖其他窗口应用程序的元素?
- 在 stl 映射中插入新项目时,将覆盖到第一个元素
- vector元素被覆盖
- 映射写入失败:无法覆盖第一个元素
- 字符串拆分为矢量<字符*>覆盖矢量元素
- 一旦满足指定容量,覆盖优先级队列末尾的元素