Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vectors not like arrays

Tags:

c++

I've been getting my head round c++ for a few months, and have been directed by google to stack overflow most of the time for c++ queries. I noted frequently exhortations of the type "why don't you use a vector", and was inspired to do just that.

So, primarily to get the minor benefits of automatic memory deallocation, and being able to write typed comparison functions for sorting. I switched an array of pointers to objects to being a vector. Now I thought (incorrectly it seems) that vectors could be used more or less like arrays, and hence I initialized thusly:

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 some time later I need to sort the vector on some attribute of the cluster object. So:

std::sort(pclust.begin(), pclust.end(), ClusterCompareNumSegs);

Again no problems compiling. Except the vector doesn't get sorted. It turns out that vector.size() is zero, and of course my initialization should have been

pclust.push_back(clusters + i);

Now that's easy to fix, but I am confused, because the initial incorrect assignment was working. I successfully iterated through the vector - using the array syntax, like so:

for (clustind=0; clustind < numClust; ++clustind) {<br>
    cluster *cl = pclust[clustind];
    ...happily access *cl...

And it all worked fine. So I'm just wondering what's going on. Presumably in my initial assignments, I was trying to access elements not yet in the vector (I was trying to put them in), and the vector was throwing exceptions that I was ignoring. But nonetheless, when referencing the locations, the pointers were there. Can anyone provide enlightenment?

like image 204
bandjalong Avatar asked May 30 '12 07:05

bandjalong


1 Answers

vector::reserve doesn't change the size of your vector, it still contains only the 0 elements it was created with. What it does is make sure that the vector can potentially hold numClust without having to reallocate. See here.

What you want is to either declare the vector to have that size

vector<cluster *> pclust(numClust);

or to resize the vector

pclust.resize(numClust);
like image 120
Benjamin Bannier Avatar answered Oct 18 '22 13:10

Benjamin Bannier