Yes, it is way costlier! I stumbled on the problem very recently and got these two very useful links in Google. Please check these out for a thorough understanding.
- The following link is helpful for core theoretical logic – https://stackoverflow.com/questions/73095254/how-is-vectorvectorint-heavier-than-vectorpairint-int
- And here the fact is experimentally proved which is cool! – https://codeforces.com/blog/entry/110222
So my take on this is:
- When we need a large vector size but a small number of walkthroughs, the vector<pair<int>> implementation has a way more advantage over vector<vector<int>>.
- When you need larger walkthroughs per index of the outside vector(maybe you do not know even the actual size of the inside vector), then it is better to declare the vector with size and later assign values to it instead of pushing back (that’s given when you declare the size of the vector!) throughout the code.
For example,
a. vector<vector<int>> v (n, vector<int> (m,0)); – When you know the size of the inside vector – m
b. vector<vector<int>> v (n); (When you are not sure what the size of the inside vector would be)
Any of these two would give slightly better performance than just declaring vector<vector<int>> v;