Loading data into a vector of structures(将数据加载到结构向量中)
问题描述
我正在尝试将一些数据从文本文件加载到结构向量中.我的问题是,你如何表示向量的大小?或者我应该使用向量 push_back 函数来动态执行此操作,如果是这样,在填充结构时这是如何工作的?
I am trying to load some data from a text file into a vector of structures. My question is, how do you indicate the size of the vector? Or should I be using a the vector push_back function to do this dynamically, and if so, how does this work when populating a structure?
完整的程序概述如下:
我的结构定义为
struct employee{
string name;
int id;
double salary;
};
文本文件 (data.txt) 包含 11 个条目,格式如下:
and the text file (data.txt) contains 11 entries in the following format:
Mike Tuff
1005 57889.9
其中Mike Tuff"是名字,1005"是id,57889.9"是薪水.
where "Mike Tuff" is the name, "1005" is the id, and "57889.9" is the salary.
我正在尝试使用以下代码将数据加载到结构向量中:
I am trying to load the data into a vector of structs using the following code:
#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;
}
当我执行此操作时,我收到一条错误消息:调试断言失败!表达式:向量下标超出范围."
When I execute this, I get an error that says: "Debug Assertion Failed! Expression: vector subscript out of range."
推荐答案
vector 是可扩展的,但只能通过 push_back(), resize() 和其他一些函数 - 如果你使用 emps[i] 并且 i 大于或等于 vector 的大小(最初为 0),程序将崩溃(如果幸运的话)或产生奇怪的结果.如果您事先知道所需的尺寸,您可以致电例如emps.resize(11) 或将其声明为 vector.否则,你应该在循环中创建一个临时的employee,读入它,并将其传递给emps.push_back().
A vector is expandable, but only through push_back(), resize() and a few other functions - if you use emps[i] and i is greater than or equal to the size of the vector (which is initially 0), the program will crash (if you're lucky) or produce weird results. If you know the desired size in advance, you can call e.g. emps.resize(11) or declare it as vector<employee> emps(11);. Otherwise, you should create a temporary employee in the loop, read into it, and pass it to emps.push_back().
这篇关于将数据加载到结构向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将数据加载到结构向量中
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
