The insertion and access times of maps are logN, but since my code has to iterate over the map again and again to find duplicates, the worst case complexity would surely be n^2 right?
ifstream infile; infile.open("test.txt");
string line;
int linecount=0;
map<string, int> TextLines;
if (infile.is_open())
{
while (getline(infile, line))
{
if (TextLines.find(line) != TextLines.end())
continue;
TextLines[line] = ++linecount;
}
}
infile.close();
//print in new file;
map<int, string> output;
map<string, int> ::iterator ite = TextLines.begin();
while (ite != TextLines.end())
{
output[ite->second] = ite->first;
ite++;
}
ofstream outfile;
outfile.open("test.txt");
map<int, string> ::iterator ite2 = output.begin();
while (ite2 != output.end())
{
outfile << ite2->second <<endl;
ite2++;
}
The find operation is a logN operation. It's in a loop of N times. So n*logN is of course, O(nLogN). The next loop of some value N or lower(if there were duplicates), this is the same for the third loop. So time complexity is O(nLogN).