Jump to content
  • Advertisement
Sign in to follow this  
ToohrVyk

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

This topic is 4451 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
Sure. Go for it.

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 - &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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!