VC++ vector iterator initialization

2019-08-26 21:50发布

问题:

I have the following deceleration in my header file

// 3D Vector
typedef struct tagV3D /*: V2D*/ {
  union {
   struct {
          double x;
          double y;
          double z;
   };
   struct {
          struct tagV2D v2d_;
   };
 };
} V3D, TVec3D, *PVec3D;

now i have a method inside my cpp file

    bool InsertSelfIntersectionVertexes(vector<PVec3D> &avtxlst) {

    PVec3D vtx;
    int iI;
    ...

    vtx = new TVec3D;
    *vtx = v;
    PVec3D* p= avtxlst.begin() + iI + 1;
    avtxlst.insert(p, vtx);

    ...
    }  

I get following errors trying to compile the code

error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'PVec3D *'
and
error C2664: 'std::_Vector_iterator<_Ty,_Alloc> std::vector<_Ty>::insert(std::_Vector_const_iterator<_Ty,_Alloc>,const _Ty &)' : cannot convert parameter 1 from 'PVec3D' to 'std::_Vector_const_iterator<_Ty,_Alloc>'

How do I Fix this?

The following code worked fine with vc6 and the errors appeared when migrated to VS 2008.
Why is that ?
Appreciate any answers

回答1:

A vector<T>::iterator is a type by itself and is not compatible with your pointer to your struct. You should create a vector<PVec3D>::iterator my_iter = avtxlst.begin().

Now you can do the same operations on your iterator, as you can with the pointer you had. Such as increment, my_iter++ or dereference *my_iter.

You can then use my_iter and increment it by Ii and whatever else you need to do.