mardi 28 mai 2019

How to index and clear properly a multidimensional vector

I am working on a piece of code that reads data from files and should save this data in a multidimensional vector. The data is stores in three columns in each file and I am saving the data from each file in a 2D vector. Then, I need to store the data from all the files into a 3D vector, in which the third index represents the number of files.

I am not sure I am doing this in the proper way and I would like some guidance. When I print the content of the vector _data, I expect it to print in each iteration of the loop only the data of the j-th file, instead it prints all of the data.

Should I clear _data after each file is read? And if so, how do I clear _data?

Thanks.

    vector< vector<double> > data(3);
    vector< vector< vector<double> > > _data;
    for (int i = 0; i < channels.size(); ++i){
        ifstream ifs(channels.at(i));
        if(!ifs){
            cerr << "File could not be found." << endl;
            exit(1);
        }
        else if(ifs.is_open()){
            string line;
            getline(ifs,line);
            while(ifs.good()){
                istringstream iss (line);
                double x;
                double y;
                double err;
                iss >> x >> y >> err;
                data[0].push_back(x);
                data[1].push_back(y);
                data[2].push_back(err);
                getline(ifs,line);
            }
            _data.push_back(data);
    }

    for ( int j = 0; j < channels.size(); ++j){
        for ( int i = 0; i < data[0].size(); ++i){
            cout << _data[j][0][i] << '\t' << _data[j][1][i] << '\t' << _data[j][2][i] << endl;
        }
        cout << "---------------" << endl;
    }

Aucun commentaire:

Enregistrer un commentaire