Creating a 2 dimensional Vector and accessing it

I've been trying to make a 2-d vector that would be a 10x10 and i could fill the vector(called nest) so that one of the indices could have more components than another other indices. But when i create the vector it makes every value in it zero. Here's my code
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Test {
  static int i;
  static int j;
 static vector<int> vec;
 static vector< vector<int> > nest;
  static int GetVec(int j) { return vec[j]; } 
 public:
  Test();
  ~Test(){};      
  static void PhillVec();
  static void TransferVec();  
};
#endif

void Test::PhillVec() {
 vec.resize(10);

    double random;
     for( int a=0; a<vec.size(); a++) { 
	  random = rand() % 10000;
	  double value = random/10000;  
	
    if( value < .5 ) vec[a]=1 ;
	else vec[a]=0;
   
	   }
   for (int j=0;j<vec.size();j++) {
   	   cout<< "vec " << j << "= " << vec[j] <<endl;  
    }
}

void Test::TransferVec () { ////here is the problem part of the code
 nest.resize(10);
 
 for(int l=0;l<10;l++)  {
        nest[l].resize(10); /////i think this makes my vectors full of zeros
        if(GetVec(l)==1){
        nest[l].push_back(1);
   cout<<"nest= "<<nest[l][i]<<endl;
    }
} 
    i++;
}

Test::Test(){
 for(int t=0;t<10;t++){
  PhillVec();
  TransferVec();    
}
}

int Test::j=0;
int Test::i=0;
vector<int> Test:: vec;
vector< vector<int> > Test:: nest;

int main() {
 srand( time(NULL) );
 Test();  
}


Any comments or suggestions would be great. Thank you.
Last edited on
forceface wrote:
nest[l].resize(10); /////i think this makes my vectors full of zeros

Yes, you are right, vector<int>::resize() fills out each expanded element with value of int() which is 0. Nothing wrong here.
How do i then create a vector that is a 10x10 but that is completely empty?
I understand that you want to create a 10x10 table, and each cell in the table is just a place holder, no any object is created at this moment. But it's impossible to directly use vector to do it. As long as you specify a size to a vector, then the vector creates objects right away, and each object is initialized with proper value. You need to define something like wrapper or referencer to approach your goal.
Last edited on
Could you possibly give me an example of what you were thinking?
For example, if you define "vector<MyClass> aaa(2);", then aaa will contain 2 objects of MyClass, this means aaa is not empty because it has 2 objects already.

if you define "vector<MyClass*> bbb(2);", then bbb will contains 2 objects of "MyClass*", but not objects of MyClass, the default value for pointer here is NULL. Now bbb's size is 2, bbb is "a sort of empty" for object of MyClass. Here MyClass* is a referencer of MyClass.
Topic archived. No new replies allowed.