【发布时间】:2019-12-01 13:12:34
【问题描述】:
我正在努力声明一个接受向量字段的循环,检查它是第一次出现还是跳转到下一个向量,直到该字段包含新字符串。
我的输入文件 (.csvx) 类似于:
No.; ID; A; B; C;...;Z;
1;1_380; Value; Value; Value;...; Value;
2;1_380; Value; Value; Value;...; Value;
3;1_380; Value; Value; Value;...; Value;
...
41;2_380; Value; Value; Value;...; Value;
42;2_380; Value; Value; Value;...; Value;
...
400000; 6_392; Value; Value; Value;...; Value;
注意:文件比较大....
我设法将我的文件解析为vector<vector<string> >,并在分号处拆分行以访问任何字段。
现在我想访问第一个“ID”,即 1_380 并从同一行存储参数,然后转到下一个 ID 2_380 并再次存储这些参数等等......
这是我目前的代码:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/algorithm/string.hpp>
using namespace std;
/*
* CSVX Reader defined to fetch data from
* CSVX file into vectors
*/
class CSVXReader
{
string fileName, delimiter;
public:
CSVXReader(string filename, string delm = ";") :
fileName(filename), delimiter(delm)
{}
vector<vector<string> > getData(); //Function to fetch data
}; //from CSVX file
/*
* Parse through CSVX file line by line
* and return the data in vector of vector
* of strings
*/
vector<vector<string> > CSVXReader::getData()
{
ifstream file(fileName);
vector<vector<string> > dataList; //Vector of vector
//contains all data
string line = "";
while (getline(file, line)) //Iterate through each line
//and split the content
//using delimiter
{
vector<string> vec; //Vector contains a row from
//input file
boost::algorithm::split(vec, line, boost::is_any_of(delimiter));
dataList.push_back(vec);
}
file.close();
return dataList;
}
int main(int argc, char** argv)
{
CSVXReader reader("file.csvx"); //Creating an object
//of CSVXReader
vector<vector<string> > dataList = reader.getData();//Get the data from
//CSVX file
for(vector<string> vec : datalist) //Loop to go through
//each line of
//dataList
//(vec1,vec2;vec3...)
if(vec[1] contains "_" && "appears for the first time")
{store parameters...};
else{go to next line};
return 0;
}
如您所见,我不知道如何正确声明我的循环... 为了清楚起见,我想检查每个向量“vec”的第二个字段:它是新的吗? -> 存储同一行的数据,如果不是 -> 跳转到下一行,即向量,直到出现新的 ID。
期待任何建议!
【问题讨论】:
-
在某个地方,您真的应该使用
std::unordered_set来记录重复和/或帮助检测重复。 -
不确定这是否适用于您的情况,但我会在数据库中导入数据,比如 sqlite,并使用标准数据库 API。
-
或者至少使用现有的 csv 库(例如 libcsv)。
-
@sklott 我宁愿只使用一个 c++ 脚本...
-
@SanderDeDycker 必须先调查一下,但感谢您的提示。