我的前横向如何混乱
How is my for-loop messing up?
我在我编写的此代码中对循环有问题。一切都很好,除了它不会在我的字符串阵列中捕获第四行的值(" jill"," jason"," jim"。(
我很确定,我的功能定义中的问题正在为"初始化"发生,因为最终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 ****nn";
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;
}
}
您的 for
循环脱离数组的界限。摆脱+1
for (int i = 0; i < arraySize; i++)
您在带有4行的2D数组中传递,但在您的初始((函数中,您循环5次:
TeamV.resize(arraySize + 1); // Why plus 1?
//iterate through teams
for (int i = 0; i < arraySize + 1; i++) // Why plus 1?
{
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]; // Because you loop four times on the
// last loop i = 4, which is outside the string
// array you passed, which has only 4 rows.
}
}
零索引是第一个,索引i = 4表示第五行,您超越了创建的数组,我得到了一个std :: bad_alloc except。
如果您从" arraysize 1"中遗漏了 1,则可以正常工作。
顺便说一句,现在的样子,它正确地填充了4行,直到抛出bad_alloc异常,所以我不明白您为什么说它遗漏了第四行。
相关文章:
- 如何克服提升精神AST混乱
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- std::result_of语法混乱
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- C++中多线程的混乱
- Arduino LCD 显示屏显示混乱的字母
- 在MSDOS编译器上,用大于最大值的值初始化int时输出混乱
- 库设计混乱.. "public"/"private"(模板)标题,库文件..?
- 常量指针上的混乱
- 智能手机代码厨师问题逻辑混乱
- 数组和指针使算术混乱
- C++智能指针混乱
- 双链表混乱
- SFML视图与窗口混乱
- 如果我将html与QTextEdit一起使用,则键入会很混乱
- 为什么我在有关文件编码格式的QT代码中获得了混乱的代码
- 双结肠混乱
- C 公共变量范围混乱
- 关于返回和参数类型的混乱
- 我的前横向如何混乱