Nimish Jain
Nimish Jain

Reputation: 21

Difference b/w std::vector<int> V(N) and std::vector<int> V[N]?

Are these 2 statements std::vector<int> V(N) and std::vector<int> V[N] equivalent??

Also what do they mean?

Upvotes: 0

Views: 86

Answers (2)

Jon Reeves
Jon Reeves

Reputation: 2586

The answer to this question comes in two parts. The first concerns basic syntax, and the second concerns semantics for the std::vector container. One of them is built into the language itself, the other is declared as part of the standard library.

Part 1:

Are these 2 statements std::vector V(N) and std::vector V[N] equivalent??

No. It appears you're confusing built-in array declaration syntax (i.e. the [] brackets), with the "array-like" semantics of the library-declared std::vector<T> object. It might help to recognize that under the hood, std::vector<T> is going to be declared as a struct or class. In a very rough sense, it will look something like this:

template<typename T>
struct vector {
    vector();
    vector(size_type count);
    ...
    T *storage;
    size_type count;
};

Here you see it will have a few different constructors, including one that takes a size_type and pre-allocates memory to store enough elements. A full list of the available constructors for std::vector can be found here.

The () syntax in your example is a call to a constructor, the behavior of which is implementation defined. The square bracket [] declaration syntax is a language feature that tells the compiler to allocate that many objects either on the stack or on the heap, depending on where the allocation occurs.

In most cases (I won't say never because there are always exceptions), you're not going to use std::vector<int> V[N] because std::vector<int> V is already a way to store an "array" of elements.

Upvotes: 1

silverfox
silverfox

Reputation: 1662

std::vector<int> V(N) creates an std::vector<int> of size N.

std::vector<int> V[N] creates an array of size N containing std::vector<int>.

You can see this from this piece of code :

#include <vector>
#include <iostream>
#include <typeinfo>
const int N = 100;

int main()
{
    std::vector<int> test(N);
    std::cout << test.size() << '\n';
    std::cout << typeid(test[0]).name() << '\n'; //output i

    int i=1; test[0] = i;  //runs fine
    //std::vector<int> i2; test[0] = i2; //converting error

    std::vector<int> test2[N];
    std::cout << sizeof(test2)/sizeof(test2[0]) << '\n';
    std::cout << typeid(test2[0]).name();

    //int i3=1; test2[0] = i3; //converting error
    std::vector<int> i4; test2[0] = i4; //runs fine
}

Result:

100
i
100
St6vectorIiSaIiEE

Edit: As @463035818_is_not_a_number and @Eljay mentioned, std::vector<int> V[N] should be written as std::array<std::vector<int>,N> for clarity.

Upvotes: 1

Related Questions