Let’s say I have two types, Class1 and Class2. Then I create two vectors:
vector<Class1> vec1;
vector<Class2> vec2;
//create vec1 and vec2, such that both have the same number of elements
for (vector<Class1>::size_type i=0; i!=vec1.size(); ++i) {
c1 = vec1[i];
c2 = vec2[i]; //BAD?
//do something
}
You probably get the picture. Isn’t it bad in this case to rely on the size_type for vector<Class2> being the same as the one for vector<Class1>?
In these cases, where you have two same-sized vectors containing objects of different types, yet they are related enough to warrant looping through both of them, how can this problem be resolved?
I know it’s unlikely that I’ll ever hit high enough integers to ever run into problems, but still, I want to write good, robust, C++ code. Maybe I should look at both size_types and take the minimum of them? Is that the way to go? Sounds like a strange practice to me.
The
std::allocatordefinessize_typeassize_t, so you can assumesize_typeassize_tiif you can guarantee there are no custom allocators that define a different type for theirsize_types.However you take the risk of someone coming back later and adding a custom allocator that may be incompatible with this assumption.