简体   繁体   中英

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

Is std::vector::begin() from prior- C++11 equivalent to std::vector::data() in C++11? The reason I'm asking this, earlier than C++11, I used to treat std::vector::begin() as a pointer but after C++11, it's not, and i cannot cast to a pointer equivalent. So, can I use data() instead after C++11?

No, begin returns an iterator, whereas data returns a pointer. For a given implementation, these may be the same thing, but you shouldn't count on this.

Using iterator as pointer is completely wrong, because of it is implementation-defined. If you still need pointer to data at iterator you should use address of dereferenced iterator, like this:

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 pointer to vector elements.

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

Depends what you mean by equivalent. Dereferencing either will yield a reference to the first item in the vector, but the iterator returned by begin() is not guaranteed to be convertible to the pointer type returned by data().

The reason I'm asking this, earlier than C++11, I used to treat std::vector::begin() as a pointer but after C++11, it's not, and i cannot cast to a pointer equivalent.

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

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

There are two iterator pairs that straddle the vector's data:

begin() to end()

and

data() to data() + size()

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

As a matter of good style you ought to use begin() to end() where you can (which will be almost always).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM