c ++ vector将所有元素存储为最后一个元素 [英] c++ vector stores all elements as last element

查看:32
本文介绍了c ++ vector将所有元素存储为最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图将矩阵数据从 xml 文件存储到 rawFaceData 向量.当我在第一个 for 循环中检查 cout 语句时,它返回我想要的向量中所有元素.但是当它跳出第一个 for 循环并进入第二个 for 循环时,cout 始终为我提供与最后一个元素完全相同的所有元素(例如,如果向量大小为 4,则 cout 给我最后一个元素)元素的值 4 次!),之前的值都消失了.谁能告诉我为什么???谢谢!

So I was trying to store the matrix data from xml file to the rawFaceData vector. when I check the cout statement in the first for loop it returns just what I want for all elements in the vector. But when it jumps out of the first for loop and goes to the second for loop, the cout gives me all the elements exactly the same as last element all the time(e.g. if the vector size is 4, then the cout gives me the last element's value 4 times!), the previous ones' values are gone. Can anyone tell me why??? Thank you!

vector<Mat> rawFaceData;
Mat temp;
FileStorage fsRead = FileStorage();
//output xml datas to a Mat vector for calculation
for(int readCount = 1; readCount < count; readCount++){
    ssfilename.str("");
    ssfilename<<name<<readCount<<postfix;
    filename = ssfilename.str();
    cout<<filename<<endl;
    fsRead.open(filename, FileStorage::READ);
    fsRead["ImageData"]>>temp;
    rawFaceData.push_back(temp);
    cout<<rawFaceData[readCount-1]<<endl;
}
//now raw image datas are now all in the Mat vector, there are count-1 elements in this vector.
//following is avg calculation of the training images.
for(int i = 0; i < rawFaceData.size(); i++){
    cout<<rawFaceData[i]<<"\n"<<endl;
}

推荐答案

OpenCV Mat 类使用共享指针和引用计数机制来存储数据并避免不需要的深拷贝.

OpenCV Mat class uses shared pointer and reference counting mechanism to store data and avoid unwanted deep copies.

每次从 FileStorage 读取数据到 temp 时,数据都会更新到相同的内存位置,并且所有对 temp 数据的引用代码> 现在指向新数据.即旧数据被覆盖.

Everytime you read the data from FileStorage into temp, the data is updated in the same memory location and all the references to the data of temp now point to the new data. i.e. the old data is overwritten.

当您将 Mat 推入向量时,数据不会复制到向量的元素中.相反,只向向量添加一个引用,并且 temp 的引用计数器递增.所以实际上,向量的所有元素都包含相同的数据.

When you push the Mat into the vector, data is not copied into the element of the vector. Instead, only a reference is added to the vector and the reference counter of temp is incremented. So actually, all the elements of the vector contain same data.

您可能希望将 temp 的深层副本 push_back 复制到向量中,如下所示:

You may want to push_back a deep copy of temp into the vector like this:

rawFaceData.push_back(temp.clone());

这篇关于c ++ vector将所有元素存储为最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆