1,105,169 Community Members

Vector range check

Member Avatar
dreday92
Light Poster
31 posts since Sep 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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();
                }

            }
Member Avatar
deceptikon
Eternally Awesome
4,669 posts since Jan 2012
Reputation Points: 1,339 [?]
Q&As Helped to Solve: 679 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
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.

Member Avatar
dreday92
Light Poster
31 posts since Sep 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
deceptikon
Eternally Awesome
4,669 posts since Jan 2012
Reputation Points: 1,339 [?]
Q&As Helped to Solve: 679 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: