C++ 需要向量超出范围错误的帮助吗
伙计们,我正在从一个文件中读取并输入一个向量,但我一直得到一个弹出框:“向量员工超出范围!”错误。这就像我试图访问并传递向量中的最后一个索引,但如果是这种情况,我看不到。。。谢谢你的帮助 文本文件:C++ 需要向量超出范围错误的帮助吗,c++,C++,伙计们,我正在从一个文件中读取并输入一个向量,但我一直得到一个弹出框:“向量员工超出范围!”错误。这就像我试图访问并传递向量中的最后一个索引,但如果是这种情况,我看不到。。。谢谢你的帮助 文本文件: 123 vazquez 60000 222 james 100000 333 jons 50000 444 page 40000 555 plant 40000 代码: #包括 #包括 #包括 #包括 使用名称空间std; struct employees{int-id;string-lname;
123 vazquez 60000
222 james 100000
333 jons 50000
444 page 40000
555 plant 40000
代码:
#包括
#包括
#包括
#包括
使用名称空间std;
struct employees{int-id;string-lname;double-salary;};
void getData(向量和列表、ifstream和inf);
int i=0;
int main()
{
字符串文件名(“file2.txt”);
向量表;
ifstream-inf;
inf.open(文件名);
获取数据(列表,inf);
inf.close();
for(无符号整数j=0;j>列表[i].工资;
i++;
}
}
当您将列表
传递到getData()
中时,其中包含零个元素。然后尝试访问索引i
(从0
开始)处的元素,但没有这样的元素,因此出现错误
您需要在容器中插入新元素;最简单的方法是创建一个临时对象,将数据读入该对象,然后将该对象插入容器
employee e;
while (inf >> e.id >> e.lname >> e.salary)
list.push_back(e);
请注意,这也修复了不正确的输入循环。在不正确的循环中,流可能达到EOF或在循环中的某个读取期间失败,但直到在while循环中增加
i
后,才能检测到这一点,每次都需要推回员工。或者你可以为你的雇员
类定义>操作符
,你甚至不需要getData
函数,你只需要通过istream\u迭代器
进入向量
构造函数
使用istream\u迭代器的示例:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
struct employee { int id; std::string lname; double salary; };
std::istream& operator>>(std::istream& is, employee& e) {
return is >> e.id >> e.lname >> e.salary;
}
int main() {
std::string filename("file2.txt");
std::ifstream inf;
inf.open(filename); //add error checking here
std::vector<employee> list((std::istream_iterator<employee>(inf)), std::istream_iterator<employee>());
for (std::vector<employee>::iterator iter = list.begin(); iter != list.end(); ++iter) {
std::cout << iter->id << " " << iter->lname << std::endl;
}
return 0;
}
#包括
#包括
#包括
#包括
结构employee{int-id;std::string-lname;double-salary;};
std::istream&operator>>(std::istream&is、员工与e){
返回值为>>e.id>>e.lname>>e.salary;
}
int main(){
std::字符串文件名(“file2.txt”);
std::ifstream-inf;
inf.open(filename);//在此处添加错误检查
std::vector list((std::istream_iterator(inf)),std::istream_iterator());
对于(std::vector::iterator iter=list.begin();iter!=list.end();++iter){
std::cout idlist[i].lname
应该是list[j].lname
注意向量的类型可能是重复的,这是一个结构…我实现了你的想法,但我得到了错误:错误C2039:“id”:不是“std::vector”的成员
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
struct employee { int id; std::string lname; double salary; };
std::istream& operator>>(std::istream& is, employee& e) {
return is >> e.id >> e.lname >> e.salary;
}
int main() {
std::string filename("file2.txt");
std::ifstream inf;
inf.open(filename); //add error checking here
std::vector<employee> list((std::istream_iterator<employee>(inf)), std::istream_iterator<employee>());
for (std::vector<employee>::iterator iter = list.begin(); iter != list.end(); ++iter) {
std::cout << iter->id << " " << iter->lname << std::endl;
}
return 0;
}