Search code examples
c++qtvectoriteratorqmap

Qt: iterator of a vector in a QMap


I am working with Qt and OpenCV and I would like to create an iterator with std::vector <cv::Rect_<int>> to have access to all cv::Rect_.
This vector is part of a QMap < int, std::vector <cv::Rect_<int>> > _facesframe;

So this is how I am trying to have access to these vectors:

                foreach (unsigned int frame , _imageGItem->_faceSampler._facesframe.keys() )
                {
                    std::vector <cv::Rect_<int>>::const_iterator it = _imageGItem->_faceSampler._facesframe.value(frame).begin();
                    if( it != _imageGItem->_faceSampler._facesframe.value(frame).end())
                    {
                        qDebug()<<"here";
                    }

                }

But the program crashes at the line if... because of an incompatible iterator.

Does someone know how to reach all cv::Rect_<int> of a QMap < int, std::vector <cv::Rect_<int>> > please?


Solution

  • This is because you are comparing iterators to different vectors.

    const T QMap::value(const Key & key, const T & defaultValue = T()) const
    

    Vector is returned by value, so this is copied.

    You should use

    T & QMap::operator[](const Key & key)
    

    to correct this:

    foreach (unsigned int frame , _imageGItem->_faceSampler._facesframe.keys() )
      {
        std::vector <cv::Rect_<int>>::const_iterator it =
                           _imageGItem->_faceSampler._facesframe[frame].begin();
        if( it != _imageGItem->_faceSampler._facesframe[frame].end())
          {
            qDebug()<<"here";
          }
    
      }
    

    or (less efficient bacause of 1 copy being made):

    std::vector <cv::Rect_<int>> v =   // this will copy
                                _imageGItem->_faceSampler._facesframe.value(frame);
    std::vector <cv::Rect_<int>>::const_iterator it = v.begin();
    if( it != v.end())
      {
        qDebug()<<"here";
      }