Class Constructor Error Help

[Edited: 2:34pm. Changed topic name to more accurately reflect problem.]

Hi everyone,

I have a very simple program that gives a runtime error. I have identified the line where I get the error, but for the life of me, I can't figure out why I get the error. Can someone please please help me out? I will be forever grateful.

To the best of my knowledge, the contructor for a class populates a vector, but when a member function tries to access that vector, there is no data in it.

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
61
62
63
64
65
66
67
68
69
#include<iostream>
#include<vector>
#include<ctime>

using namespace std;

class class_v {

  vector<vector <double> > vV;
public:
  class_v();
  double get_if(int, int);
  double get_mem(int, int);
};

class_v::class_v(){
  vector< vector <double> >vV;
  for (int i = 0; i<10000; i++){
    vV.push_back(vector <double> (5000, 1));
  }
  for (int i = 0; i<10000; i++){
    vV.at(i).at(0) = 0;
  }
  cout << vV.size() << endl;
}

double class_v::get_mem(int i, int j){
  return vV.at(i).at(j); // <----- the runtime error is at this line.
}

double class_v::get_if(int i, int j){
  if (j==0){
    return 0;
  }
  else{
    class_v::get_mem(i, j);
  }
}

int main() {
  class_v my_vector;
  time_t mem_start, mem_end;
  time_t if_start, if_end;
  double mem_diff, if_diff;


  time(&mem_start);
  
  for (int i = 0; i < 10000; i++ ) {
      my_vector.get_mem(i,0);
  }
   
  time(&mem_end);
  mem_diff = difftime(mem_end, mem_start);
  cout << "memory access took "<< mem_diff << endl;

  time(& if_start);
  for (int i = 0; i < 10000; i++) {
    my_vector.get_if(i, 0);
  }
       
  time(& if_end);
  if_diff = difftime(if_end, if_start);
  cout << "if took " << if_diff << endl; 

  return 0;
       
}
Last edited on
The size of vV.at(i) is zero (examine it with cout << vV.at(i).size();) . The at function will throw an out_of_range exception if the requested position is equal to or greater than the size.

Last edited on
Thanks for your comment. My confusion still remains: I think that I am populating vV when I call the constructor for class_v. Line 24
 
  cout << vV.size() << endl;
returns 10000 which means that the vector was initialized alright.

But when I try to access it again with
 
vV.at(0).at(0)
I get an out_of_range error, which means that vV no longer holds any data. What am I doing wrong?
Ok, I found the problem. It is line 17, which should not be there.
Just for completeness,

cout << vV.size() << endl;

is NOT the same as

cout << vV.at(i).size();

The first one is the size of vV, which was 10000 elements.
The second is the size of the object in the first element, which was 0.

Last edited on
Topic archived. No new replies allowed.