这是我的代码:
#include <iostream>
#include <stdexcept>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct TeamS
{
int ID;
string MEMBERS[3];
};
//Vector initialization
void Initialize (vector<TeamS> & TeamV, const int id[], const string m[][3], int arraySize)
{
for(int i=0 ; i<4 ; i++)
{
TeamV.at(i).ID = id[i];
for(int j=0 ; j<3 ; j++)
{
TeamV.at(i).MEMBERS[j]=m[i][j];
}
}
}
void printList (const vector <TeamS>& TeamV)
{
for(int i=0 ; i<4; i++)
{
cout<<"Information for team "<<i<<endl;
cout<<TeamV[i].ID;
for(int j=0 ; j<3 ; j++)
{
cout<<" "<<TeamV[i].MEMBERS[j]<<" ";
}
cout<<endl;
}
}
int main(int argc, char** argv)
{
short int choice;
cout<<"Starting Initialization"<<endl;
vector<TeamS> TeamV;
const int ID [4] ={ 123, 321, 456, 789};
const string MEMBERS [4] [3] = { {"Sarah", "Joe", "John"}, {"Chris", "Kevin", "James"}, {"Tom", "Kim", "Emily"}, {"Jill", "Jason", "Jim"} };
cout<<"Ending Initialization"<<endl;
Initialize (TeamV, ID ,MEMBERS, 4);
cout<<"**** Team List **** "<<endl;
//printList(TeamV);
cout<<"************************************************************************"<<endl;
while(1)
{
cout<<"Enter 1 to see a list of teams"<<endl;
cout<<"Enter 2 to add a team to the list"<<endl;
cout<<"Enter 3 to search for a team using an ID"<<endl;
cout<<"Enter 4 to end the program"<<endl;
cout<<endl<<"Enter Choice : ";
cin>>choice;
if(choice == 1)
{ printList(TeamV); }
else if(choice == 2)
{ }
else if(choice ==3 )
{ }
else if(choice == 4)
{ exit(0); }
}
return 0;
}
每当我编译它时,它会给我错误终止程序'std:out_of_range' 什么&lt;&gt ;: vector :: _ M_range_check 我在代码中找不到问题,但看看你可能有什么东西
答案 0 :(得分:2)
你真的没有在你的矢量上添加任何东西。您的Initialize()
以:
TeamV.at(i).ID = id[i];
但如果TeamV
为空,则会抛出out_of_range
。你可能打算这样做:
TeamV.push_back(TeamS()); // NOW, there's something in it
TeamV[i].ID = id[i];
更好的是将构造函数添加到带有id和某些成员的TeamS
,以便循环可以是:
for (int i = 0; i < 4; ++i) {
TeamV.push_back(TeamS(id[i], m[i]));
}
或者在C ++ 11中:
std::vector<TeamS> TeamV{
{123, {"Sarah", "Joe", "John"}},
{321, {"Chris", "Kevin", "James"}},
...
};
答案 1 :(得分:0)
您似乎在主函数中创建了矢量TeamV并将其留空。它没有任何元素。但是你打电话给Initialize(TeamV,...)
。在这
您试图通过at()
访问TeamV的元素,但它是空的!