Matt Kline
Matt Kline

Reputation: 10507

Converting vector iterator to a member pointer

I've loaded a text file into a buffer, and wanting to use good C++ style, used a vector<char>. I then wanted to pass an iterator from said vector to a char* function argument - I assumed that under the hood, a vector iterator just resolves to a pointer to the member type. However, I get the following error:

no known conversion for argument 2 from ‘const __gnu_cxx::__normal_iterator<char*, std::vector<char> >’ to ‘char*’

Is a vector iterator not just a pointer? Would just using a pointer be more efficient in that case?

Upvotes: 1

Views: 10014

Answers (3)

dchhetri
dchhetri

Reputation: 7136

Since we are dealing with std::vector<char> and vectors are guaranteed to be contiguous in memory, you can do func( &(*iteratorVariable) ); that just deferences the value and returns the address.

Upvotes: 5

Andrey Tuganov
Andrey Tuganov

Reputation: 361

Pointers can be used as iterators, but vector::iterator is not a pointer. All these operations would essentially give you the same pointer:

   &v[it-v.begin()]
   v.data() + (it-v.begin())
   &v.front() + (it-v.begin())
   &(*it)    // this one is less safe than others

However, you should consider if you actually need to convert iterators to pointers. If you need a pointer, better use an index: &v[i].

Upvotes: 2

Brian Neal
Brian Neal

Reputation: 32399

Some old implementations might implement iterators as pointers, but you should not rely on this. They are separate types. It is hard to say if they are more efficient because you haven't shown your code. In general they can be just as efficient as pointers, but some compilers use special checked versions of iterators in debug mode that are slower because they do run-time checks for programmer errors.

Another way to convert from iterators to pointers in C++11:

#include <vector>

void foo(char*) {}

int main()
{
    std::vector<char> v = { 'a', 'b', 'c' };
    auto it = v.begin() + 1;
    char* p = v.data() + (it - v.begin());
    foo(p);
    return 0;
}

Upvotes: 3

Related Questions