Sign in to follow this  
ToohrVyk

[C++] : ptrdiff_t and std::vector

Recommended Posts

Since the index i of a vector element is guaranteed by the standard to be equal to &v[i] - &v[0], the ptrdiff_t type can be used to store vector indices, right?

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Since the index i of a vector element is guaranteed by the standard to be equal to &v[i] - &v[0], the ptrdiff_t type can be used to store vector indices, right?


With the problem of the idiomatic name - ptrdiff_t is supposed to be used to store the difference between two pointers, not indices :). Anyway, it should work.

Share this post


Link to post
Share on other sites
Quote:
Original post by omgomghilol
What's wrong with int?

In practice, maybe nothing. In theory, the size of int is a problem. int is not guaranteed to be large enough to address any possible index in an array. Say int is 32 bits and you're on a 64-bit system with 64-bit pointers. You can then create arrays so large that an int cannot access them. That's why there is a need for "special" types for indices and such. They are guaranteed to be large enough.

Share this post


Link to post
Share on other sites
Quote:
Original post by rip-off
Whats wrong with std::vector::size_type?


I have a tree, with each node having 4 children. The children may be a vector index (which means another node) or a pointer offset (which means a leaf). In order to avoid the overhead tied to using variant types (especially when both types might be different in size for certain implementation), I have chosen to use the largest of the two. Bear in mind that this use is private and in a single, short class, and that outside the class ptrdiff_t will only be used as pointer offsets.

Share this post


Link to post
Share on other sites
std::vector<T>::size_type is always a good choice

you probably won't go wrong with std::size_t

int is just wrong - why do you want to be able to represent negative indexes / sizes??

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this