2-dimensional vector

Is there a way initialalizing a two dimensional matrix other than using an array?
closed account (48bpfSEw)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>

using namespace std;

int main ()
{
  typedef vector<vector<int> >  V2D;
  typedef V2D::iterator         ItV2D;

  V2D           v2d;
  vector<int>   v1,
                v2;
  
  v1.push_back(1);
  v1.push_back(2);
  v1.push_back(3);
  v2d.push_back(v1);
  
  v2.push_back(4);
  v2.push_back(5);
  v2.push_back(6);
  v2d.push_back(v2);

  for (ItV2D it1=v2d.begin(); it1!=v2d.end();++it1) {
    cout << "next it1: ";

    for (vector<int>::iterator it2=(*it1).begin(); it2 != (*it1).end(); ++it2) {
      cout << *it2 << ", ";
    }
    
    cout << endl;
  }
  
  return 0;
}



output:
next it1:1,2,3,
next it1:4,5,6
That's complicated at my skill level :-)
So i have to engaging me at deeper learning into iterators and such stuff.

Is it somehow doable implementing it in such way getting access on values via v2d.val( row,col), or, even better: v2d[row][col] ?

Thanks, Nico

*edit: After a close look and thinking over I believe I understand now your code :-)
Last edited on
Is it somehow doable implementing it in such way getting access on values via V2D.get( row,col), or, even better: V2D[row][col] ?


Certainly it's possible:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <vector>

using namespace std;

typedef vector<int> IntRow;
typedef vector<IntRow> IntTable;

int main()
{
  IntTable table(10); // 10 rows

  for (size_t row = 0; row < table.size(); row++)
  {
    table[row].resize(10); // set each row to 10 cols
  }

  // fill table
  for (size_t row = 0; row < table.size(); row++)
  {
    for (int col = 0; col < table[row].size(); col++)
    {
      table[row][col] = row + col;
    }
  }
  // display table
  for (size_t row = 0; row < table.size(); row++)
  {
    for (size_t col = 0; col < table[row].size(); col++)
    {
      cout << table[row][col] << '\t';
    }
    cout << '\n';
  }
  system("pause");
  return 0;
}
Cool. It shows to me how ingenious the C++ language is. At table[row][col] are working just two overloaded operator[] functions consecutive from left to right, I guess :-)
table[row] returns a vector, so you access this vector with second []
Yep, i had seen a simple vector implemetation in a teaching book. The [] at vector is an overloaded operator.
But It was behind my imagination for that such an operator function could be used deliver the argument of another such, so that this could applied in consecutive manner. But when i think about, i see that my_vector[col][row] is basically similar to the overloaded << operator (cout << var1 << var2)
Put a note somewhere to check out Lisp at some point in the future :).
Topic archived. No new replies allowed.