muhammadhasan01's blog

By muhammadhasan01, 10 months ago, In English

I recently came across Jiangly's code, where I learned a "shorter" way to create multidimensional vectors in C++.

Instead of the conventional syntax:

vector<vector<vector<int>>> dp(n, vector<vector<int>>(m, vector<int>(k)));

You can use this shorter syntax:

vector dp(n, vector(m, vector<int>(k)));

I'm not sure which C++ version supports this syntax (probably C++11 or later).

Although the shorter syntax doesn't really make it really "short" as opposed to creating multidimensional array, I think this is worth knowing.

Is there any shorter syntax for multidimensional vector in C++? I know we can use this blog's template, though we might need to copy paste the template first.

  • Vote: I like it
  • +72
  • Vote: I do not like it

»
10 months ago, # |
  Vote: I like it +26 Vote: I do not like it
vector dp(n, vector(m, vector(k, 0)));
»
10 months ago, # |
  Vote: I like it -6 Vote: I do not like it

In fact it came out in C++14. It's automatically type deducing. The similar one which uses that is:

vector<int> a = {3, 1, 2, 5, 4};
sort(a.begin(), a.end(), greater<>());