gpt4 book ai didi

c++ - 需要有关 vector 超出范围错误的帮助

转载 作者:搜寻专家 更新时间:2023-10-31 01:20:14 27 4
gpt4 key购买 nike

伙计们,我正在读取一个文件并输入到一个 vector 中,但我不断收到一个弹出框:“vector 员工超出范围!”错误。这就像我试图访问传递 vector 中的最后一个索引,但如果是这种情况我看不到......任何帮助表示赞赏文本文件:

123 vazquez 60000
222 james 100000
333 jons 50000
444 page 40000
555 plant 40000

代码:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

struct employees { int id; string lname; double salary; };
void getData(vector<employees>& list, ifstream& inf);
int i = 0;
int main()
{
string filename("file2.txt");
vector<employees> list;
ifstream inf;
inf.open(filename);

getData(list, inf);
inf.close();

for(unsigned int j = 0; j < list.size(); j++)
{
cout << list[j].id << " " << list[i].lname << endl;
}

system("pause");
return 0;
}

void getData(vector<employees>& list, ifstream& inf)
{
int i = 0;
while(inf)
{
inf >> list[i].id >> list[i].lname >> list[i].salary;
i++;
}
}

最佳答案

当您将 list 传递给 getData() 时,它的元素为零。然后您尝试访问索引 i 处的元素(从 0 开始),但是没有这样的元素,因此出现错误。

您需要向容器中插入新元素;最简单的方法是创建一个临时对象,将数据读入该对象,然后将该对象插入容器。

employee e;
while (inf >> e.id >> e.lname >> e.salary)
list.push_back(e);

请注意,这也会修复您不正确的输入循环。在您不正确的循环中,流可能会到达 EOF 或在循环中的一次读取期间以其他方式失败,但您直到递增 i 后才检测到这一点。

关于c++ - 需要有关 vector 超出范围错误的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5112315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com