-3
#include<bits/stdc++.h>
#include<vector>
using namespace std;
int main(){
    
    int n=5;
    vector<vector<int>> v;
    v[0][0]=1;
    v[1][0]=1;
    v[1][1]=1;
    cout<<2;    //not getting output 2

}

In the above code I am trying to make a dynamic 2D array but the thing is that I am not getting any error but the number 2 is also not getting printed. What may be the reason?

Deepak Silver
  • 27
  • 1
  • 3
  • The presence of both `#include` and `#include` suggests you don't know how to use bits/stdc++.h. [Here's a bit of reading to help you out with that](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). TL;DR version: It's an implementation helper file. Don't directly include it. – user4581301 Nov 17 '21 at 05:10
  • Vector-of-vector is a poor choice for a "dynamic 2D array", if you are talking 2D arrays in the traditional sense (where every row has the same number of columns). If that's what you're trying to do, stop immediately. You're better off allocating a single vector of size `width * height`, encapsulating that in a class, and using operator overloading to provide 2D indexing. – paddy Nov 17 '21 at 05:23
  • [Example of Paddy's comment](https://stackoverflow.com/a/2076668/4581301) – user4581301 Nov 17 '21 at 16:38
  • @paddy I would not say never. Sure for production or performance critical code. But for toy examples or class assignments with elements in the order of tens or even hundreds I don't see the need to complicate the code with flatten arrays, especially since C++ doesn't have anything native for that. – bolov Nov 18 '21 at 00:03
  • That's a fair call. My motivation is to discourage practicing bad habits. The semantics of vector-of-vector implies something that _can_ and most likely _will_ have rows of different lengths. So it's an appropriate structure for that, or as you say for one-off toy examples. A compiler handles native 2D arrays as flat, and random-access indexing is `row * ncols + col` internally. To emulate this, one could do the same thing with a [basic wrapper](https://godbolt.org/z/sMjb6789z). Sure, it's more than a toy, but only a little bit more. It also fits better with common array usage patterns. – paddy Nov 18 '21 at 04:40

1 Answers1

2

The default constructor of vector creates an empty vector. You are accessing vector elements beyond the vector size which is Undefined Behavior.

You can initialize the vector with initializer lists:

std::vector<std::vector> v{
   {1},
   {1, 1}
};
bolov
  • 72,283
  • 15
  • 145
  • 224