Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D vector vs 1D vector

In C++11, how does a 2D vector against 1D vector in terms of time?
In the 2D vector given, all the inner vectors are of the same size.

Ex:

std::vector<std::vector<int>> X{10, std::vector<int>(4)};

vs

std::vector<int> Y(40);

Which avatar of the vector would perform better when the elements are randomly accessed?

like image 679
letsBeePolite Avatar asked Dec 18 '25 13:12

letsBeePolite


1 Answers

A single std::vector is inherently simpler, it's just a contiguous block of memory stored somewhere.

A std::vector of std::vector has more overhead but it's also more powerful (since each inner vector can be of different size, for example).

Random access performance should be benchmarked thoroughly for your specific pattern of usage but the main difference is that:

  • with single vector you just compute size_t index = x + y*WIDTH and access the element
  • with nested vector you have two levels of indirection, first you must obtain the memory containing the inner vector, then you must obtain the memory of the data of the inner vector.
like image 73
Jack Avatar answered Dec 21 '25 04:12

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!