1

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?

4

3 回答 3

5

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.

于 2013-06-09T03:13:13.480 回答
3

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;
}
于 2013-06-09T03:32:08.390 回答
2

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].

于 2013-06-09T14:50:50.713 回答