'std::out_of_range'

I'm sure I didn't do anything wrong here...

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
vector< vector< vector<int> > > M;
if(database.is_open()){
  int user, item, time, result;
  while(getline(database, line)){
    stringstream getint(line);
    getint >> user >> item >> result >> time;

    if(M.size()<user){
      M.resize(user+1);
      if(M.at(user).size()<item){
        M.at(user).resize(item+1);
        if(M.at(user).at(item).size()<(time-1318348785+1)){
          M.at(user).at(item).resize(time-1318348785+1, 0);
        }
      }
      else{
        if(M.at(user).at(item).size()<(time-1318348785+1)){
          M.at(user).at(item).resize(time-1318348785+1, 0);
        }
      }
    }
    else{
      if(M.at(user).size()<item){
        M.at(user).resize(item+1);
        if(M.at(user).at(item).size()<(time-1318348785+1)){
          M.at(user).at(item).resize(time-1318348785+1, 0);
        }
      }
      else{
        if(M.at(user).at(item).size()<(time-1318348785+1)){
          M.at(user).at(item).resize(time-1318348785+1, 0);
        }
      }
    }

    M.at(user).at(item).at(time-1318348785) = result;
  }
}
database.close();

Message I get:
1
2
terminate called after throwing an instance of 'std::out_of_range'
  what(): vector::_M_range_check:__n (which is 1775045) >= this->size() (which is 1775045)

I tried to use tb in gdb to debug, and I get something is wrong with the call of at(). But I don't know what was wrong...
Hi,

Are you sure you need a 3d vector? They consume memory very quickly. That is probably what has happened if it is trying to access subscript 1775045

What is the real life problem you are trying to solve here, someone might be able to come up with something better :+)

Edit: Could you please not start another topic for this, just keep your other one going. Respondents wind up saying the same things as each other, wasting their time. Bdanielz suggested looking at other data structures, which is what my suggestion will eventually involve.
Last edited on
What if a 'line' does not contain four integers?
What if the 'time' is small? Negative index is out of range too.


Overall, does all that branching help?
1
2
3
4
if ( M.size() < user ) M.resize( user+1 );
if ( M.at( user ).size() < item ) M.at( user ).resize( item+1 );
if ( M.at( user ).at( item ).size() < time ) M.at( user ).at( item ).resize( time+1 );
M.at( user ).at( item ).at( time ) = result;



How sparse is your table?
Will there be many "empty" indices?
Will they be used?
Could std::map be a more logical container?
Okay. I will answer in my old topic.
if(M.size()<user){ should be: if(M.size()<=user){

because if M.size() == user then user is not a valid index into M.
Topic archived. No new replies allowed.