This might be a really stupid question, but how do I optimize this code in making it more effiecient (faster,less memory consuming)? I made this code to help me sort some text files. It reads each string from the first file, then it searches through the second file until it finds all related strings, and in a third file it writes some matched strings. Here is the code:
ifstream h("SecondFile.txt");
ifstream h2("FirstFile.txt");
ifstream uh("MatchedStrings.txt");
ofstream g("sorted.txt");
int main()
{
string x, y, z;
cout << "Sorting..." << endl;;
while (!h.eof()){
h >> x;
while (!h2.eof() || (y == x)){
h2 >> y;
uh >> z;
if (y == x){
g << z << endl;
break;
h2.clear();
h2.seekg(0);
uh.clear();
uh.seekg(0);
}
}
if (h2.eof() && (y != x)){
g << "none" << endl;
h2.clear();
h2.seekg(0);
uh.clear();
uh.seekg(0);
}
}
cout << "Finished!";
}
I have changed my code to this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream h("SecondFile.txt");
ifstream h2("FirstFile.txt");
ifstream uh("MatchedStrings.txt");
ofstream g("sorted.txt");
int main()
{
string x;
bool write_none = true;
int i = 0,l=0;
string check[] = {""};
string unhashed_checked[] = { "" };
string sorted_array[] = { "" };
cout << "Sorting..." << endl;
//Get to memory
while (!h2.eof())
{
h2 >> check[i];
uh >> unhashed_checked[i];
i++;
}
while (!h.eof()){
h >> x;
write_none = true;
for (int t = 0; t <= i;t++)
{
if (x == check[t])
{
break;
write_none = false;
sorted_array[l] = unhashed_checked[i];
l++;
}
}
if (write_none)
{
sorted_array[l] = "none";
l++;
}
}
for (int k = 0; k <= l; k++)
{
g << sorted_array[k]<<endl;
}
cout << "Finished!";
}
But I am getting this exception when running the program:
Unhandled exception at 0x01068FF6 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC
Suppose the number of strings in your files are n and m, respectively.
The way you're doing it now, the complexity is Θ(n m). Moreover, the complexity constants are those of file operations, which are incredibly slow.
Instead, you should just read one of the files into a std::unordered_*
container, then compare keys between the containers. This should reduce the running time to expected Θ(n + m).
As a side note, you might want to look at more modern ways to read strings into containers (using, e.g., std::istream_iterator
).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments