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

Started by
6 comments, last by RDragon1 17 years, 9 months ago
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?
Advertisement
Sure. Go for it.
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.
Whats wrong with std::vector::size_type?
What's wrong with int?
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.
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.

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??

This topic is closed to new replies.

Advertisement