我在编写此代码时遇到了for循环问题。一切都运行正常,除了它没有捕获我的字符串数组中的第4行的值(“Jill”,“Jason”,“Jim”。)
我很确定问题发生在我的'Initialize'函数定义中,因为我的vector没有捕获最终ID和团队成员最终列表的值。作为参考,输出很好,直到最后的TeamV元素。我已经尝试过搞乱这些指数了,但我已经碰到了一堵砖墙。提前致谢。
#include <vector>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
const int NUM_TEAMS = 4;
const int NUM_MEMBERS = 3;
struct TeamS {
int id;
string m[NUM_MEMBERS];
}TeamV, tempTeam;
void Initialize(vector <TeamS> & TeamV, const int id[],
const string m[][NUM_MEMBERS], int arraySize);
void printList(const vector <TeamS> & TeamV);
int main()
{
const int ID[NUM_TEAMS] = { 123, 321, 456, 789 };
const string MEMBERS[NUM_TEAMS][NUM_MEMBERS] =
{
{ "Sarah", "Joe", "John" },
{ "Chris", "Kevin", "James" },
{ "Tom", "Kim", "Emily" },
{ "Jill", "Jason", "Jim" }
};
vector<TeamS> TeamV;
Initialize(TeamV, ID, MEMBERS, NUM_TEAMS);
cout << TeamV[3].m[1];
printList(TeamV);
// not working on my installation at home -> system("pause");
cin.get();
}
void Initialize(vector<TeamS>& TeamV, const int id[], const string m[][NUM_MEMBERS], int arraySize)
{
//Resizes a TeamS vector and then modifies it's values to match the information provided
TeamV.resize(arraySize+1);
//iterate through teams
for (int i = 0; i < arraySize+1; i++)
{
TeamV[i].id = id[i];
//iterate through members of teams
for (int j = 0; j < NUM_MEMBERS; j++)
{
TeamV[i].m[j] = m[i][j];
}
}
}
void printList(const vector<TeamS>& TeamV)
{
cout << "**** Team List ****\n\n";
int teamVSize = TeamV.size();
for (int i = 0; i < teamVSize; i++)
{
cout << "Information for team " + to_string(i) << endl;
cout << "ID:\t" << TeamV[i].id << "\t";
for (int j = 0; j < NUM_MEMBERS; j++)
{
cout << TeamV[i].m[j] << "\t";
}
cout << endl;
}
}
答案 0 :(得分:2)
您的for
循环超出了数组的范围。摆脱+1
for (int i = 0; i < arraySize; i++)
答案 1 :(得分:2)
你传入一个包含4行的2D数组,但在你的initialise()函数中你循环了5次:
public Comparable[] common(Comparable[] a, Comparable[] b) {
// List is more flexible, but the toArray at the end is a bit costly. You can probably figure a better way of doing this.
List<Comparable> res = new ArrayList<>();
int indexA = 0;
int indexB = 0;
while (indexA < a.length && indexB < b.length) {
// Exercice for the reader: replace with compareTo calls
if (a[indexA] == b[indexB]) {
// Common item!
res.add(a[indexA]);
indexA++;
indexB++;
} else if (a[indexA] < b[indexB]) {
// item in A is smaller, try the next
indexA++;
} else {
indexB++;
}
}
return res.toArray(new Comparable[0]);
}
零索引是第一个,索引i = 4表示第5行,你超出了你创建的数组,我得到了一个std :: bad_alloc异常。
如果你从&#34; arraySize + 1&#34;中省略了+ 1;它工作正常。
顺便说一下,现在的方式是,它正确地填充了4行,直到它抛出bad_alloc异常,所以我不明白为什么你说它排除了第4行。