【问题标题】:Loading data into a vector of structures将数据加载到结构向量中
【发布时间】:2011-07-03 21:02:48
【问题描述】:

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

执行此操作时,我收到一条错误消息:“调试断言失败!表达式:向量下标超出范围。”

【问题讨论】:

    标签: c++ vector struct


    【解决方案1】:
    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));
    }
    

    【讨论】:

    • 好主意,但原始代码使用了ifstream,而不是cin
    【解决方案2】:

    vector 是可扩展的,但只能通过push_back()resize() 和其他一些函数——如果您使用emps[i]i 大于或等于vector 的大小(最初为 0),程序将崩溃(如果幸运的话)或产生奇怪的结果。如果您事先知道所需的尺寸,您可以致电例如emps.resize(11) 或将其声明为 vector&lt;employee&gt; emps(11);。否则,你应该在循环中创建一个临时的employee,读入它,并将它传递给emps.push_back()

    【讨论】:

    • 天哪,你是天使!让它与以下新的 while 循环完美配合:while(fileIn) { employee temp; getline(fileIn, temp.name); fileIn &gt;&gt; temp.id; fileIn &gt;&gt; temp.salary; fileIn.ignore(1); emps.push_back(temp); i++; }
    • 您还可以使用insert 将结构放置到指定位置,而push_back 始终附加到向量的末尾。
    • @user633055:很高兴听到这个消息;您在此处显示的代码是我的想法。如果您满意,您应该将您的首选答案标记为已接受;这将使您将来提出的问题更有可能得到回答。 :-)
    • @AJG85: 确实——但是在使用insert() 插入大向量时要小心(除非你总是插入接近末尾),因为这样的操作的性能很差(因为所有元素插入位置的右侧必须向右移动一个插槽)。 (我假设您知道这一点,@AJG85;此信息针对 OP。)
    • @Aasmund 是的,当然,我只是提到了其中一个值得了解的“少数其他功能”:P
    猜你喜欢
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多