Convert iterator to pointer?

前端 未结 12 2310
野性不改
野性不改 2020-12-14 14:20

I have a std::vector with n elements. Now I need to pass a pointer to a vector that has the last n-1 elements to a function.

F

12条回答
  •  情书的邮戳
    2020-12-14 14:41

    A safe version to convert an iterator to a pointer (exactly what that means regardless of the implications) and by safe I mean no worries about having to dereference the iterator and cause possible exceptions / errors due to end() / other situations

    #include 
    #include 
    #include 
    
    int main()
    {
        std::vector vec;
    
        char itPtr[25];
        long long itPtrDec;
        
        std::vector::iterator it = vec.begin();
        memset(&itPtr, 0, 25);
        sprintf(itPtr, "%llu", it);
        itPtrDec = atoll(itPtr);
        printf("it = 0x%X\n", itPtrDec);
        
        vec.push_back(123);
        it = vec.begin();
        memset(&itPtr, 0, 25);
        sprintf(itPtr, "%llu", it);
        itPtrDec = atoll(itPtr);
        printf("it = 0x%X\n", itPtrDec);
    }
    

    will print something like

    it = 0x0

    it = 0x2202E10

    It's an incredibly hacky way to do it, but if you need it, it does the job. You will receive some compiler warnings which, if really bothering you, can be removed with #pragma

提交回复
热议问题