Stop allocating memory:
- Don't copy vectors around, pass by const ref instead
- Don't make new strings when a string_view will do
- Don't make new vectors when you can reuse the old one
- Don't make a string from a char*, just to turn it back into a char* (this one is very minor since you only do it once)
- Output directly to avoid creating a temporary string in makeCSVLine
With all that, here's what I came up with:
#include <fstream>
#include <string>
#include <string_view>
#include <vector>
using std::string;
using std::string_view;
using std::vector;
void splitStr(string_view line, const char delimiter, vector<string_view>& splitLine)
{
splitLine.clear();
for(;;) {
std::size_t pos = line.find(delimiter);
if (pos == string_view::npos) {
splitLine.push_back(line);
return;
}
splitLine.push_back(line.substr(0, pos));
line = line.substr(pos+1, string_view::npos);
}
}
template<typename T>
void makeCSVLine(T& out, const vector<string_view>& splitLine)
{
out <<
splitLine[0] << ',' <<
splitLine[1] << ',' <<
splitLine[3] << ',' <<
splitLine[4] << ',' <<
splitLine[5] << ',' <<
splitLine[6] << ',' <<
splitLine[10] << ',' <<
splitLine[9] << ',' <<
splitLine[11] << ',' <<
splitLine[7] << ',' <<
splitLine[32] << '\n';
}
int main(int argc, char* argv[])
{
if(argc < 3)
{
exit(EXIT_SUCCESS);
}
const char* inPath = argv[1];
const char* outPath = argv[2];
std::ifstream inFile;
std::ofstream outFile;
inFile.open(inPath);
outFile.open(outPath);
vector<string_view> split;
string line;
while(std::getline(inFile, line))
{
splitStr(line, ';', split);
if(split[3][0] == 'E' || split[3][0] == 'T')
{
makeCSVLine(outFile, split);
}
}
inFile.close();
outFile.close();
}