简体   繁体   中英

Error while pushing a std::pair in std::vector

I found doing a push in

Template < class a, class b > 
std::vector < std::pair < a, b > >::push_back(...)

almost always creates a segmentation fault.

I looked around for a bit and found there was an error being raised from stl_uninitialized.h (line 269).

The easiest work around I found was to reserve required / some large space for the vector and then do the push back. It worked but I'm not convinced. Why would there be an error

(My initial code is not even templated. It was with the fields

std::pair < float, cv::RotatedRect > 

I templated here for people to be able to give generic answers).

Declaration of localDetections :

std::vector < std::vector < std::pair < float, cv::RotatedRect> > > localDetections; localDetections.resize(m_allSizes.size());

where m_allSizes is a vector of no. of sizes that will be used to search and populate . Also the for condition is :

for (int sit = 0 ; sit < m_allSizes.size(); sit++) {

Place where it is used :

  cv::RotatedRect oupRect; cv::Point2d src_center(img.cols/2., img.rows/2.); rotateRectInSpace(newRect, oupRect, src_center, -(rotatedAngle)); std::pair<float, cv::RotatedRect> newPair((float)finval, oupRect); localDetections[sit].push_back(newPair); 

sit is a variable in for loop which goes from 0 through the size of localDectections.

There is a potential bug in your code where sit could overflow into negative numbers. You may want to convert sit to be vector::size_type , or just use iterators, or push_back vectors onto localDetections as part of your loop instead of resizing beforehand.

Alternatively, something bad may be going on when you are trying to copy or assign cv::RotatedRect oupRect .

There are a lot of unknowns on this one. There's nothing obviously wrong with the code posted. A debugger is going to help more than StackOverflow.

You need to allocate memory for locaDetections first, using localDetections.resize or something like that.

localDetections needs to contains at least sit positions allocated before you call:

localDetections[sit].push_back(newPair);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM