1

I am new to cpp STL I have a doubt regarding array of vectors when we declare array of vectors like vectors <int> arr[100]; we can also say this as a 2-D matrix .But we if talk about 2-D arrays (int prr[100][100]) then prr[0] then it will print the address of first array in 0th row Basically i want to ask why we are declaring vector <int> arr[100] because arr[0] will also store address of array at 0th array we should declare like vector <int*> arr[100] for declaring array of vectors

2
  • 1
    FWIW, if you want a matrix you use a std::vector<data_type> in a class and fake that it has multiple dimensions using math. This gives you the most performance. Commented Dec 29, 2018 at 6:25
  • There is no such thing as vectors<int> in the C++ standard library. However, std::vector<int> arr[100] is an array of one hundred std::vector<int>, which can be used - with care - AS IF it is a 2-D matrix. The number of elements of each std::vector<int> depends on what the program does. Commented Dec 29, 2018 at 6:36

1 Answer 1

3

But we if talk about 2-D arrays (int prr[100][100]) then prr[0] then it will print the address of first array in 0th row

That is true to some extent and in some contexts.

prr[0] is an object of type int [100] -- an array of 100 ints.

In some contexts, prr[0] decays to a pointer to its first element, however it is not always true.

sizeof(prr[0]) will be 100 * sizeof(int).
&prr[0] will be of type int (*)[100), pointer to "array of 100 ints", not int**.

In contrast,

Basically i want to ask why we are declaring vector <int> arr[100] because arr[0] will also store address of array at 0th array we should declare likevector <int*> arr[100] for declaring array of vectors

No, arr[0] will not store the address of the array at 0-th array. arr[0] is of type std::vector<int>. It's simple as that. Unlike an array, an object of type std::vector<int> does not decay to a pointer to the first element of the object in any context. Hence any further comparisons with int* does not make sense.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.