1.11M Members

Vector range check

 
0
 

Can someone tell me why I get this error
"terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Abort trap"

when i run the following code? user and reservations are vectors of two classes

        else if (str == "lookup")
        {
            getline(cin, Name, '\n');
            if (Name == user.at(i).getName()) 
            {
                for (int i = 0; i < user.size() ; i++)
                {
                    cout << user.at(i).getName();
                    cout << user.at(i).getphone();
                    cout << reservations.at(i).getflight();
                    cout << user.at(i).getdate();
                }

            }
 
0
 

By using the at() member function, out of range indices will throw std::out_of_range. So I'd wager i is out of range for the reservations vector given that i is bound to the size of the user vector. Though you've also got some fun looking scope hiding going on with i that may be doing unexpected things.

 
0
 

I figured it was that but when i change user.size() in the for loop to a constant variable it still gave me the same error

 
0
 

when i change user.size() in the for loop to a constant variable

Unrelated things are unrelated. The loop is bound to the size of user, but you assume (apparently incorrectly) that reservations is large enough to use any index valid for user.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: