0

vector of vector initialization and assignment

Hi, Refer code below: int rows = 5; int cols = 10; //One Way { vector<vector<int>> vec(rows, vector<int>(cols, 0)); } //Other way { vector<vector<int>> vec; vector<int> temp; temp.resize(cols); fill(temp.begin(), temp.end(), 0); vec.resize(rows); fill(vec.begin(), vec.end(), temp); } I know first code version is efficient compared to second one and will always choose 1 over 2 as far as possible. However, assume that vec is a class member and need to be initialized in constructor based on argument of rows and cols count. Is second option the only way to do initialization or there is an effective method available for same?

10th Sep 2024, 8:41 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 ответов
10th Sep 2024, 10:01 AM
Bob_Li
Bob_Li - avatar
+ 3
just a tip, vector<vector<T>> is a bad data structure, performance would suffer due to heap indirection : the problem with nesting vectors (or any other container for that matter) is that you add more and more indirections. so an element access needs to follow more and more pointers through memory. If you instead have a single array and linearly index into it, you only have to do a single address computation and can directly get your value. write yourself a class Matrix that contains a single vector<T>, then you can take advantage of the C++23 multidimensional subscript operator : https://en.cppreference.com/w/cpp/language/operators#Array_subscript_operator C++23 Core language features: https://en.cppreference.com/w/cpp/23
10th Sep 2024, 11:21 AM
MO ELomari
MO ELomari - avatar
+ 3
Thanks MO ELomari for wonderful tip
10th Sep 2024, 11:39 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 3
MO ELomari Yes, good point and useful link. But C++23...🙄
10th Sep 2024, 11:44 AM
Bob_Li
Bob_Li - avatar
+ 1
Sounds good. As member initializer works, it should be ok with below price of code as well vector<vector<int>> a; a = vector<vector<int>>(15,vector<int>(10,-1)); I thought vector of vector is only initialized , not deep copied
10th Sep 2024, 10:23 AM
Ketan Lalcheta
Ketan Lalcheta - avatar