[英]Loading data into a vector of structures
我试图将文本文件中的一些数据加载到结构向量中。 我的问题是,你如何表明矢量的大小? 或者我应该使用向量push_back函数动态执行此操作,如果是这样,填充结构时这是如何工作的?
完整的计划概述如下:
我的结构定义为
struct employee{
string name;
int id;
double salary;
};
并且文本文件(data.txt)包含以下格式的11个条目:
Mike Tuff
1005 57889.9
其中“Mike Tuff”是名称,“1005”是id,“57889.9”是薪水。
我试图使用以下代码将数据加载到结构的向量中:
#include "Employee.h" //employee structure defined in header file
using namespace std;
vector<employee>emps; //global vector
// load data into a global vector of employees.
void loadData(string filename)
{
int i = 0;
ifstream fileIn;
fileIn.open(filename.c_str());
if( ! fileIn ) // if the bool value of fileIn is false
cout << "The input file did not open.";
while(fileIn)
{
fileIn >> emps[i].name >>emps[i].id >> emps[i].salary ;
i++;
}
return;
}
当我执行此操作时,我收到一条错误消息:“调试断言失败!表达式:向量下标超出范围。”
std::istream & operator >> operator(std::istream & in, employee & e)
{
return in >> e.name >> e.id >> e.salary; // double not make good monetary datatype.
}
int main()
{
std::vector<employee> emp;
std::copy(std::istream_iterator<employee>(std::cin), std::istream_iterator<employee>(), std::back_inserter(emp));
}
vector
是可扩展的,但只能通过push_back()
, resize()
和一些其他函数 - 如果你使用emps[i]
并且i
大于或等于vector
的大小(最初为0),程序会崩溃(如果你很幸运)或产生奇怪的结果。 如果您事先知道所需的大小,可以调用例如emps.resize(11)
或将其声明为vector<employee> emps(11);
emps.resize(11)
vector<employee> emps(11);
。 否则,您应该在循环中创建一个临时employee
,读入它,并将其传递给emps.push_back()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.