Ask*_*ner 0 c++ vector push-back
我有以下数据结构作为名为"任务"的类:
private:
string name;
int computation_time;
int period;
Run Code Online (Sandbox Code Playgroud)
此外,我有一个ASCII文件与此内容:
A 3 10
B 2 12
C 1 11
Run Code Online (Sandbox Code Playgroud)
name = A,computation_time = 3,period = 10等等......
现在我想在文件中读取,创建Task-object并将其推回到向量中:
void read_in_task_list_and_create_tasks(const string &filename, vector<Task> ¤t_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));
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我查看current_tasks向量时,它有元素,但它们的值与我的in_file值不匹配.观看已注释的线条.tmp_task对象是完全正确的,但如果它被推回,它就会丢失它的值,就像上面描述的那样.
这可能是Task-class中的Copy-Constructor问题,因为std :: vector正在管理内存分配吗?
我在Linux x86上使用带有g ++编译器的netbeans.
谢谢
至少IMO,你采取了一些错误的方法,试图自己做太多的工作.标准库已经可以处理您正在进行的大部分工作.您真正需要做的就是指定如何从流中读取单个对象:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用标准算法实际读取数据并将其放入向量中:
void read_in_task_list_and_create_tasks(const string &filename,
vector<Task> ¤t_tasks)
{
std::ifstream in(filename.c_str());
std::copy(std::istream_iterator<Task>(in),
std::istream_iterator<Task>(),
std::back_inserter(current_tasks));
}
Run Code Online (Sandbox Code Playgroud)
作为奖励,这也将解决你看到两次读取文件中的最后一项所遇到的问题因为你的循环错误(是的,我知道你没有提到这一点,但根据你编写循环的方式,它是基本上是不可避免的).
| 归档时间: |
|
| 查看次数: |
535 次 |
| 最近记录: |