将数据加载到结构向量中

2021-12-21 00:00:00 struct vector c++

我正在尝试将一些数据从文本文件加载到结构向量中.我的问题是,你如何表示向量的大小?或者我应该使用向量 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;emps(11);.否则,你应该在循环中创建一个临时的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().

相关文章