Andre Viau
Andre Viau

Reputation: 275

Vectors and Pointers syntax

What is the diffrence beatween say:

Vector<int*> myVector[5] and Vector<int> *myVector[5]

The way I see it, in the first case, my vector will contain 5 counts of pointers to ints. In the second case, myVector is a pointer to an array of 5 ints.

The reason I ask is because I wrote some code a while back and now I don't understand it any more.

With Vector<int> *myVector[5], why can I do

for(int i = 0; i < 5; i++)
        {
            myVector[i] = new Integer(13);
        }

I know for a fact that the operator new returns a pointer, and then I'm storing it in myVector, but a pointer to an int is not an int right? I'm confused.

Upvotes: 1

Views: 322

Answers (4)

Gerald
Gerald

Reputation: 23499

The way I see it, in the first case, my vector will contain 5 counts of pointers to ints. In the second case, myVector is a pointer to an array of 5 ints.

No. In the first case, you will have 5 Vector<int*> objects, and in the second case you will have 5 Vector<int> objects. A Vector<int*> is (probably) a vector of pointers to integers. A Vector<int> is (probably) a vector of integers. So what you will essentially have is a 2-dimensional array, though one dimension would be a dynamic array (vector).

I know for a fact that the operator new returns a pointer, and then I'm storing it in myVector, but a pointer to an int is not an int right? I'm confused.

A pointer to an int is not an int, but it can be stored as an int, at least on 32-bit Windows.

But in your case, that's not what's happening. A pointer to an Integer is being stored as a pointer to a Vector<int>. Perhaps on some older versions of Visual C++ the code would compile as it allowed implicit conversions between different pointer types. On newer versions it shouldn't compile.

Upvotes: 0

tyger
tyger

Reputation: 181

When using Vector *myVector[5], myVector is not a pointer to an array of 5 ints, but an array of 5 pointers which point to vector.

Vector<int> *myVector[5];
for(int i = 0; i < 5; i++)
{
    myVector[i] = new Integer(13);
}

Here, myVector[i] is an pointer of vector. I don't think this piece of code can compliles. Would you give some detail about class Integer?

Upvotes: 1

Ray Tayek
Ray Tayek

Reputation: 10003

std::vector<int*> myVector[5]; // array of vector of pointer to int
std::vector<int> *myVector2[5]; // array of pointer to vector of int
for(int i=0;i<5;i++)
    myVector[i]=*new std::vector<int *>(2);
int j=42;
myVector[0].push_back(&j);
for(int i=0;i<5;i++)
    myVector2[i]=new std::vector<int>(2);
myVector2[0]->push_back(j);

Upvotes: 0

Alok Save
Alok Save

Reputation: 206536

Vector<int*> myVector[5]

Creates an array of size 5 to Vector<int*>.

 Vector<int> *myVector[5]

Creates an array of 5 pointers to Vector<int>.
Instead, Using vector to vector is a cleaner soution:

vector<vector<int> > myVector(5);

Upvotes: 0

Related Questions