0

我有以下数据结构作为名为“任务”的类:

private:
string name;
int computation_time;
int period;

此外,我有一个包含以下内容的 ASCII 文件:

A 3 10
B 2 12
C 1 11

名称 = A,计算时间 = 3,周期 = 10 等等....

现在我想读入文件,创建任务对象并将其推回向量中:

void read_in_task_list_and_create_tasks(const string &filename, vector<Task> &current_tasks)
{
    ifstream in_file;
    in_file.open(filename.c_str());

    string tmp_name;
    int tmp_computation_time;
    int tmp_period;

    while(!in_file.eof())
    {
        in_file >> tmp_name;
        in_file >> tmp_computation_time;
        in_file >> tmp_period;

//        Task tmp_task(tmp_name, tmp_computation_time, tmp_period);
//        current_tasks.push_back(tmp_task);
        current_tasks.push_back(Task(tmp_name, tmp_computation_time, tmp_period));
    }
}

现在,当我查看 current_tasks 向量时,它有元素,但它们的值与我的 in_file 值不匹配。观看注释掉的行。tmp_task 对象是完全正确的,但如果它被推回,它就会失去上面描述的值。

这可能是任务类中的复制构造函数问题,因为 std::vector 正在管理内存分配吗?

我在 Linux x86 上使用带有 g++ 编译器的 netbeans。

谢谢

4

3 回答 3

5

确保没有定义复制构造函数或赋值运算符。

自动的应该完全符合您的要求。

于 2010-11-18T21:27:46.590 回答
5

至少国际海事组织,你采取了一些错误的方法,试图自己做太多的工作。标准库已经可以处理您正在做的大部分事情。您真正需要做的就是指定如何从流中读取单个对象:

struct Task { 
    std::string name;
    int computation_time;
    int period;
};

std::istream &operator>>(std::istream &is, Task &t) {
    return is >> t.name >> t.computation_time >> t.period;
}

然后您可以使用标准算法来实际读取数据并将其放入您的向量中:

void read_in_task_list_and_create_tasks(const string &filename, 
                                        vector<Task> &current_tasks) 
{
    std::ifstream in(filename.c_str());

    std::copy(std::istream_iterator<Task>(in), 
              std::istream_iterator<Task>(),
              std::back_inserter(current_tasks));
}

作为奖励,这也将解决您似乎两次读取文件中的最后一项的问题,因为您的循环错误(是的,我知道您没有提到这一点,但根据您编写循环的方式,它是基本上是不可避免的)。

于 2010-11-18T21:35:39.993 回答
2

Task 是否定义了复制构造函数和赋值运算符?当您将对象推入向量时,它并没有将那个确切的对象推入,而是在复制它。因此,我相信您需要定义其中一个(我不记得是哪个,但是如果您定义任何一个,那么定义两者总是好的)。

于 2010-11-18T21:22:52.717 回答