I'd like to store position in container for random access. Which data type should I use? Should I go for (unsigned int), container::size_type, or something else?
I'd like to store position in container for random access. Which data type should I use? Should I go for (unsigned int), container::size_type, or something else?
What container?
You can, technically, get into trouble with signed/unsigned mis-matches when storing indexes, so using, 'container::size_type' would actually be the universally safest way to store it, but in general using an unsigned int is also safe...I'm trying to remember when I had a problem with this, I think I was using 'int' and not 'unsigned int' (an int is signed by default) and somehow I ran into a problem doing this.
I'm not immature, I'm refined in the opposite direction.
container::size_type would probably be best, but unsigned int should be ok also. I would create a typedef for the container if you think it is at all possible that you will be changing the container type. That way you won't have to update the places you refer to its size_type.
>> An iterator.
What if an operation on the container has invalidated its iterators? Storing the position will be safe in that case.
I don't think that's accurate. A vector's iterator is a random access iterator. But if you add items to the end causing a reallocation that iterator will become invalid even though the index is still in range.