4

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?

1
  • thanks for correction, that was my perception which I wrote in a wrong way apology. But still the main question is independent of that part.
    – Ritesh
    Oct 10, 2018 at 11:17

1 Answer 1

13

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');
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.