A vector is sequential; there is something at every position
between 0 and classList.size()
, and nothing elsewhere. In the case of
pointers (and some other things), the contents can be a null
pointer, so while there is something, it is a very special
something, which can be considered nothing at a higher level.
If that's what you're looking for:
void
Base::addClass( int index )
{
if ( classList.size() <= index ) {
classList.resize( index + 1 );
}
if ( classList[index] == nullptr ) {
classList[index] = new Class();
}
}
First make sure that the vector is big enough, then test for the
nullptr
.
The vector will still contain entries for every index up to
classList.size()
. If you call addClass
once, with an
index
of 1000000, that's going to mean a lot of empty entries.
If this is your use case, then you should probably consider some
sort of sparce data structure (perhaps a std::map<int,
Class*
). If the index
aren't sparsely distributed, the
vector solution is good.
And one last point: it's almost never appropriate to use
std::vector<>::at()
. If an out of bounds index is
a programming error, you want the program to crash (which is the
usual behavior in non-optimizing builds); what you don't want in
case of a program error is to unwind the stack (in the usual
case—there are exceptions).