Home > Enterprise >  C pointer to iterator
C pointer to iterator

Time:04-22

I'm looking at some 20 year old C code and trying to bring it up to date. The code was last compiled under visual studio 2003 and I am trying to build it with visual studio 2022.

I'm looking at a piece of code right now that doesn't compile. I have an std::vector<float>. It looks like a float* is passed to a method that requires an iterator. As near as I can figure, there used to be an implicit conversion between pointers and iterators. Does this make any sense? Anybody remember?

CodePudding user response:

I have an std::vector<float>. It looks like a float* is passed to a method that requires an iterator

A raw pointer is a valid iterator. Iterators were designed to mimic pointers.

So, if a function takes an iterator and is passed a raw pointer, it should compile just fine, in all versions of C . A std::vector<T> iterator is allowed to be implemented as a raw T* pointer.

On the other hand, if a function takes a raw pointer and is passed an iterator, there is no guarantee that will compile, since an iterator is not required to be implemented as a raw pointer, and never has been. Are you sure this is not actually the case in your situation?

CodePudding user response:

I think I have seen this before, I drafted the below to show you an example but please don't use this (it's literally s***):

#include <iostream>
#include <vector>
#include <cassert>

struct Vector
{
    std::size_t m_size = 0;
    float* m_begin = nullptr;
    std::size_t size() const
    {
        return m_size;
    };
    
    void resize(const std::size_t n, float d = 0)
    {
        m_begin = (float*)malloc(n * sizeof(float));
        for(std::size_t i = 0; i < n; i  )
            *(m_begin   i) = d;
        m_size = n;
    };
    
    float& operator[](const std::size_t i) const
    {
        assert(i < m_size);
        return *(m_begin   i);
    }
};

void add(float* start, std::size_t size, float shift)
{
    for(std::size_t i = 0; i < size; i  )
        *(start   i)  = shift;
}
int main() 
{
    Vector v;
    v.resize(3, 2);
    float& x = v[0];
    std::cout << x << std::endl;
    add(v.m_begin, v.m_size, 100);
    std::cout << x << std::endl;
    return 0;
}

The add takes as input float* this also works with matrices i.e. float**.

  • Related