Iโve been going to C ++ for several months now, google has directed the stack overflow most of the time for C ++ requests. I often noted exhortations like โWhy don't you use a vector,โ and was inspired to do just that.
So, first of all, to get the small advantages of automatically freeing memory, and the ability to write typed comparison functions for sorting. I switched an array of pointers to objects in a vector. Now I thought (incorrectly) that vectors could be used by more or less similar arrays, and therefore I was initialized this way:
cluster clusters[LOTS]; vector<cluster *> pclust; pclust.reserve(numClust); for (int i=0; i<numClust; ++i) pclust[i] = clusters + i;
No complaints from the compiler. Then after some time I need to sort the vector by some attribute of the cluster object. So:
std::sort(pclust.begin(), pclust.end(), ClusterCompareNumSegs);
Again there is no compilation of problems. Except that the vector is not sortable. It turns out that vector.size () is zero, and of course my initialization should have been
pclust.push_back(clusters + i);
Now this is easy to fix, but I'm confused because the initial assignment was incorrect. I successfully went through the vector - using array syntax, for example:
for (clustind=0; clustind < numClust; ++clustind) {<br> cluster *cl = pclust[clustind]; ...happily access *cl...
And everything turned out fine. So Iโm just wondering whatโs going on. Presumably, in my original assignments, I tried to access the elements were not yet in the vector (I tried to insert them), and the vector throws exceptions, which I ignored. But, nevertheless, when indicating the locations, the signs were there. Can anyone give enlightenment?