从矢量中读取并分配给对象的成员

时间:2014-11-20 07:38:08

标签: c++

我从一个看起来像这样的输入文件中读取:

T1 23 0

T2 50 6

T3 40 8

推回3个向量,process_id,run_time,arrival_time

我有一个类进程//有成员字符串ID,int run_time,int arrival_time

3个向量的第一个元素属于第一个进程对象,依此类推。这样做:是我的问题..

#include <iostream>
#include <istream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <stdio.h>
#include <string>
#include <sstream>
#include"process.h"

using namespace std; 
int main()
{
    ifstream file;
    file.open("C:/Users/Ejada/Desktop/input.txt");

    string line;
    vector<string> process_id;
    vector<string> run_time;
    vector<string> arrival_time;
    vector<process> p; //process is a class with members string ID; int run_time; int arrival_time

    while(file.good() && (getline(file, line)))
    {
        istringstream iss(line);
        string a, b, c;
        iss >> a >> b >>c;

        if(a != "")
        {
            process_id.push_back(a);
            run_time.push_back(b);
            arrival_time.push_back(c);
        }
        else break; 
    }
    // at this point I have 3 filled vectors

////////////////////////PROBLEM IS IN THIS LOOP////////////////////////////

    for(int i=0; i<process_id.size(); i++) //take from 3 vectors to fill each process object
    {
        p.at(i).ID.push_back( process_id.at(i)); //error no suitable conversion
        p.at(i).run_time.push_back (stoi(run_time.at(i)));// error expression must have class type
        p.at(i).arrival_time.push_back (stoi(run_time.at(i))); // error expression must have class type
    }

    file.close();
    return 0;
}

3 个答案:

答案 0 :(得分:1)

当您到达循环时p向量为空,但主要问题是process的成员不是向量。

重构您的代码:

while (getline(file, line))
{
   // ...
}

vector<process> p(process_id.size());  // Create vector with appropriate number of elements

for (int i = 0; i < process_id.size(); i++) 
{
    p.at(i).ID = process_id.at(i);
    p.at(i).run_time = stoi(run_time.at(i));
    p.at(i).arrival_time = stoi(arrival_time.at(i));
}

答案 1 :(得分:0)

进入第二个循环时,p向量仍为空。因此at调用将失败。此外,您似乎希望分配给p[i]的成员,而不是使用push_back

答案 2 :(得分:0)

向量p当前是emtpy,因此'p.at()'不会返回任何内容。 p包含具有成员ID,run_time和arrival_time的'进程'类对象 - 它们不是向量,因此没有'push_back'操作。 尝试:

process entry;
entry.ID = process_id[i];
entry.run_time = stoi(run_time[i]);
entry.arrival_time = stoi(run_time[i]);
p.push_back(entry);