Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does row major form exist for vectors?

It's very clear that row major form of a 2D array is a single array stored such that different rows are aligned in sequence.

To traverse any element of the 2d array I can always do :

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

for(int i=0;i<3*3;i++){

cout<<*(*a+i)<<" "; //row major form concept where i<m*n;

}

gives:

1 2 3 4 5 6 7 8 9

It completely works for me but whenever I do this with a vector it throws me an error:

vector<vector<int> > v={{1,2,3},{4,5,6},{7,8,9}};

int m=v.size();
int n=v[0].size();
for(int i=0;i<m*n;i++){

cout<<*(*v+i)<<" ";

}

It gives :

no match for ‘operator*’ (operand type is ‘std::vector<std::vector<int> >)

I hope that vectors do follow the row major form concept as arrays. If yes than what is alternative for row major in case of a vector?

like image 740
Ritesh Avatar asked Dec 10 '22 04:12

Ritesh


1 Answers

You are on the wrong track. Since std::vector allocates memory dynamically on the free-store, there is no such thing as row-major or column-major.

Memory for a 2d-array int foo[][]{ { 1, 2, 3 }, { 4, 5, 6 } } starting at &foo[0]:

1, 2, 3, 4, 5, 6

Visualized:

+------+
| foo  |
+------+ 
|  1   |
|  2   |
|  3   |
|  4   |
|  5   |
|  6   |
+------+ 

Memory for a std::vector<std::vector<int>> foo{ { 1, 2, 3 }, { 4, 5, 6 } }:

somewhere (unrelated to &foo):

1, 2, 3

somewhere else:

4, 5, 6

Visualized:

                                                             +------+
                                                        +--> | int  |
+-------------------------+                             |    +------|
| foo                     |                             |    |  1   |
+-------------------------+       +------------------+  |    |  2   |
| std::vector<int> *data -|-----> | std::vector<int> |  |    |  3   |           
+-------------------------+       +------------------+  |    +------+      
                                  | int* data[0]-----|--+
                                  | int* data[1]-----|--+    +------+
                                  +------------------+  +--> | int  |
                                                             +------+
                                                             |  4   |
                                                             |  5   |
                                                             |  6   |
                                                             +------+

To traverse your std::vector of std::vectors:

for (auto const &v_item : v) {
    for (auto const &i : v_item) {
        std::cout << i << ' ';
    }
}
std::cout.put('\n');
like image 88
Swordfish Avatar answered Jan 03 '23 01:01

Swordfish