0

I am new to C++ programming. Can anyone please explain to me what is the difference in following statements?

vector<int> *v;
v = new vector<int>[10];

I am trying to understand the code of hashing with chaining on this link https://www.geeksforgeeks.org/c-program-hashing-chaining/

hellow
  • 12,430
  • 7
  • 56
  • 79
chetan tamboli
  • 161
  • 2
  • 13
  • 2
    The first one is a declaration, the second one is an assignment. You might want to read up on various other basics, like differences between stack and free storage allocation, difference between declaration and definition, the One Definition Rule, basic datatypes, differences between pointers and references and more. sites like cppreference.com and isocpp.org/faq are good ressources. – Loebl Aug 03 '18 at 12:07
  • 11
    I would run away from any learning resource that had lines like *either* of those – Caleth Aug 03 '18 at 12:08
  • 4
    unless those lines of code were found in a section titled "*practices to avoid*" I would look for a different tutorial. – Zinki Aug 03 '18 at 12:10
  • 1
    May I recommend [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? Resources you are using are really not giving you best information – Yksisarvinen Aug 03 '18 at 12:39
  • I would like to emphasize that the second statement would not even work without the first one. This is like asking "what is the difference between buying a car and driving a car". – Max Langhof Aug 03 '18 at 12:39
  • The first is a pointer to a single `vector`. There is no guarantee that there are other vectors following this one in memory. The second line, `new vector[10]`, allocates an array of 10 `vector` in dynamic memory and returns a pointer to the first element of the array. – Thomas Matthews Aug 03 '18 at 15:04

2 Answers2

4

First one is a variable declaration. Type of v is pointer to vector<int>. Second, memory for 10 vectors<int> is allocated and vectors are constructed. They are initially empty. v is now pointing to the allocated space, and can be used as an array of vector<int>.

0

It is a bad way to do

std::vector<std::vector<int>> v;
v.resize(10);

Why? You have a raw pointer, should be either std::shared_ptr or std::unique_ptr.

These simplify ownership and thereby insures the correct deallocation and safety.

But its usually much more safe to use the standard containers to keep this kind of information.

Surt
  • 15,501
  • 3
  • 23
  • 39