-5

What is the difference between vector<int*> a and vector<int> *a? I have problems working with pointer and vectors. I can fill the vector with this code.

    plate p;
    vector<plate*> A;
    A.push_back(&p);

But I can't find out how to work with the values after that.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
jofri
  • 131
  • 1
  • 16
  • `vector a` declares a vector containing `int*`s (pointers to `int`s). You can access an element at index `i` with `a[i]`. `vector *a` is a pointer to a vector containing `int`s and most likely not what you want. – Zinki May 30 '18 at 14:11
  • 3
    everybody has problems working with pointers, simply dont use them: `std::vector a; a.push_back(plate());` – 463035818_is_not_an_ai May 30 '18 at 14:11
  • The two have very little in common. One is a vector of pointers, the other is a pointer to a vector of `int`s. – Igor Tandetnik May 30 '18 at 14:11
  • 1
    if you have problems you should show the problematic code (the one you show here looks fishy but in principle it is fine) and include the error messages in the question – 463035818_is_not_an_ai May 30 '18 at 14:13
  • "A collection of locations" (e.g. your address book) vs "the location of a collection of things" (e.g. the address of an office). – molbdnilo May 30 '18 at 14:36
  • On a side note, it's almost always wrong to store the result of applying `&` to something for later. – molbdnilo May 30 '18 at 14:39

2 Answers2

2

vector<int*> a is a vector of integer pointers.

  • to access the value of an item one would do *a[0] or *at.at(0) read as "take the 0th item in the vector a, and then take the value that it points to"

vector<int>* b is a pointer to a vector of integers

  • to access the value of an item one would do (*b)[0] or b->at(0) read as "take the vector pointed to by b, and then take the 0th item from it".

Note that the "at" version will perform bounds checking ensuring that you have the element; but I added it to show the various syntax's available.

As stated in the comments though, raw pointers are used less and less; in addition one has to manage their lifetime very carefully (in your example would require p to live at least as long as A) and c++ has become better at moving objects around where they support it.

You should consider taking a look at The Definitive C++ Book Guide and List for any additional help regarding pointers.

UKMonkey
  • 6,941
  • 3
  • 21
  • 30
0
vector<int*> a;

In this case, variable a is a vector that contains integer pointers

vector<int> *a

And in this case, a is a pointer used to store address of a vector variable

Below is an example for you, I hope you can see the differences between them:

int var1 = 0, var2 = 1;
vector<int*> a;
a.push_back(&var1);
a.push_back(&var2);

vector<int>* b;
vector<int> c;
c.add(var1);
c.add(var2);

b = &c;
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30