简体   繁体   中英

Why do we need to use std::vector::pointer to access elements?

Usually we could use vector array accessor to access the element and modify the element, why do we need the pointer?

http://msdn.microsoft.com/en-us/library/7e4tx21z(VS.71).aspx

The presence of the convenience typedef named pointer in std::vector is no different from the presence of the myriad other typedef s like value_type , reference , allocator_type , size_type ... You can find the full list here . These aliases are very useful in generic settings. Lets say you are writing a generic function which accepts some containers and would like to create an instance of type T* where the container contains objects of type T . For the std::vector (generic type V , say) specialization(may apply to a bunch of other STL containers as well), you could get this type as typename V::value_type * or more simply as typename V::pointer .

If you think pointer type in std::vector is unnecessary, I'd say it's not.

vector can be treated as a managed, dynamically-sized array, it does support all meaningful operations which arrays can do, even it has compatible memory layout and can be used as an array in many cases.

If you can access element in array via pointer, it should be doable in vector , too.

The pointer type is the simplification of T * as vector is a template.

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