checking for duplicate

I want to check for duplicates in list of names, and get rid of those duplicates by using bool subprogram. This is my code so far. I really have no idea on how to start this

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
#include <cctype>

// for conversion to lower case lettering
class toLower {public: char operator() (char c) const {return tolower(c);}};

bool checkDuplicate(string lowerName, int n)
bool result = false; // initial
return result;

int main()
const int MAX_NAMES = 8; // capacity
int nNames = 0; // initially empty
string name[MAX_NAMES];
string lowerName[MAX_NAMES];

// ask user to type input filename
ifstream fin;
string fileName;
cout << "Enter input filename: ";
getline(cin, fileName);;
if (!fin.good()) throw "I/O error"; // output error message if file not found

//read and save the names
while (fin.good())
string aName;
getline(fin, aName);
if (aName.length() > 0)
// add record to list, if it's not full
if (nNames < MAX_NAMES)
name[nNames++] = aName;

int i;

// copying to variable lowerName for lower case conversion
for (i = 0; i < nNames; i++)
lowerName[i] = name[i];

for (i = 0; i < nNames; i++)
transform(lowerName[i].begin(), lowerName[i].end(), lowerName[i].begin(), toLower());

cout << endl;

// check for duplicates names
for (i = 0; i < nNames; i++)
if (checkDuplicate(lowerName[i], nNames))

fin.close ();

} // main

First of all it is a bad idea to declare class toLower for converting a character to the lower case because it is difficult to distinguish these two names toLower and tolower. When i saw the code the first time I thought that this declaration shall not be compiled due to the similarity of the names.

As for your function of determining duplicates then it can look for example the following way (I am assuming that there is directive using namespace std; in your code):

bool checkDuplicate( const string lowerName[], int n )
	for ( const string *next = lowerName; next != lowerName + n; ++next )
		const string *p = lowerName;
		while ( p != next && *p != *next ) ++p;
		if ( p != next ) return ( true );

	return ( false );

Last edited on
Instead of using an array of std::string, why don't you use a std::map to store your names, if you then use the name as a key you can use the ::find function to check if you already have the name in the map before you add a duplicate in the first place.
also, if you use a map, it's actually not possible to have to keys that are the same
also, if you use a map, it's actually not possible to have to keys that are the same

Exactly, that's why you have to do a find on the map with the key aka name you are contemplating on adding to the map, if it already exists then don't attempt to add it again.
you don't actually need to do the find because if you try to add a key that already exists then map::insert() will return false
Topic archived. No new replies allowed.