Is std :: vector :: begin () from priorC ++ 11 equivalent to std :: vector :: data () in C ++ 11?

Is std::vector::begin() from the previous C++11 equivalent to std::vector::data() in C ++ 11? The reason why I ask for this, before C ++ 11, I used to treat std :: vector :: begin () as a pointer, but after C ++ 11 it is not, and I can not use the equivalent of a pointer . So, can I use data () instead of C ++ 11?

+5
source share
3 answers

No, begin returns an iterator, while data returns a pointer. For this implementation, this may be the same thing, but you should not count on it.

+8
source

Using an iterator as a pointer is completely wrong, as it is defined by the implementation. If you still need a pointer to the data on the iterator, you should use the address of the dereferenced iterator, for example:

 std::vector<int> v; v.push_back(42); std::vector<int>::iterator it = v.begin(); int * p = &*it; 

And of course, in C ++ 11 you can use .data() as a pointer to vector elements.

+3
source

Is std :: vector :: begin () from previous C ++ 11 equivalent to std :: vector :: data () in C ++ 11?

Depends on what you mean by equivalent. Selecting will get a reference to the first element in the vector, but the iterator returned by begin () cannot be converted to the type of pointer returned by data ().

The reason why I ask for this, before C ++ 11, I used to treat std :: vector :: begin () as a pointer, but after C ++ 11 this is not the case, and I can not drop the pointer equivalent .

Your code worked with good (or bad) luck, depending on how you look at it.

So, can I use data () instead of C ++ 11?

There are two pairs of iterators that share vector data:

begin() to end()

and

data() to data() + size()

you can use either in any standard algorithm, and the result will be the same.

In a good style, you should use begin() to end() where you can (which will almost always be).

+2
source

All Articles