将数据加载到结构的向量中 [英] Loading data into a vector of structures

查看:114
本文介绍了将数据加载到结构的向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文本文件加载一些数据到结构的向量。我的问题是,你如何指明矢量的大小?或者我应该使用向量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;
}

当我执行这个,我得到一个错误:Debug Assertion Failed !表达式:向量下标超出范围。

When I execute this, I get an error that says: "Debug Assertion Failed! Expression: vector subscript out of range."

推荐答案

A 向量是可扩展的,但只有通过 push_back() resize() c $ c> emps [i] 和 i 大于或等于向量的大小(这最初是0),程序会崩溃(如果你幸运)或产生奇怪的结果。如果您事先知道所需的尺寸,则可以致电例如 emps.resize(11)或声明为向量< employee> emps(11); 。否则,你应该在循环中创建一个临时员工,读入它,并将其传递给 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().

这篇关于将数据加载到结构的向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆