I have a large data in text file in form:
1 0.933 2 0.865 3 0.919 4 0.726
2 0.854 3 0.906 4 0.726
2 0.882 5 0.853 4 0.897
.
. etc
every integer number follows with its float value. I want to read this file line by line, and store each line in list. I know how to do that using array of linked lists, but, I couldn't fix the memory leak. I read that it is better to use STL instead. Example:
list 1= 1 0.933 2 0.865 3 0.919 4 0.726
list 2= 2 0.854 3 0.906 4 0.726
list 3= 2 0.882 5 0.853 4 0.897
.
.
I'm not sure if the (vectors of lists) is similar to the (array of linked lists). I have tried different ways but all my attempts failed.
#include "stdafx.h"
#include <vector>
#include <list>
#include <iostream>
#include <map>
#include <sstream>
#include <iterator>
#include <fstream>
struct MyData{
int Item;
float Prob;
};
std::istream& operator>>(std::istream &is, MyData&d)
{
return is >> d.Item >> d.Prob;
}
int main()
{
std::ifstream in("DataF.txt");
std::string line;
int i = 0;
while (std::getline(in, line)) {
typedef std::istream_iterator<MyData> MyDataIstrIt;
std::stringstream ss(line);
std::vector< std::list< MyData> > data3{ MyDataIstrIt(ss), MyDataIstrIt() }; // here I couldn't fix the extractor definition for the vectors of lists
// another attempt
/*std::vector<MyData> data{ MyDataIstrIt(ss), MyDataIstrIt() };
std::vector< std::list< MyData> > data2;
data2.push_back(std::vector<MyData>()); // I read this is important for memory leak
data2.push_back(data);*/
// data2[i].push_back(data);
// ++i;
}
system("PAUSE");
return 0;
}
std::vector<std::unordered_map<int, float>>for this if the order of each line's items isn't mandatory. If it is required to be sorted I would usestd::vector<std::map<int, float>>. If the original exact order is required, then usestd::vector<std::vector<MyData>>>or a similar construct. The first two maintains theintas an index, which has its benefits.