Challenge description is here need to find the first non repeated character from the string:
Write a program which finds the first non-repeated character in a string.
Input sample:
The first argument is a path to a file. The file contains strings.
For example:
yellow tooth
Output sample:
Print to stdout the first non-repeated character, one per line.
For example:
y t
Please let me know can I improve my solution.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstring>
void findNonRepeatedChar( const std::string& record)
{
auto pred= [&record] ( char a, char b){
return strchr( record.c_str(), a ) < strchr( record.c_str(), b );
};
std::map< char, int, decltype(pred) > stringMap(pred);
for( auto elem : record )
{
auto it = stringMap.find( elem );
if( it != std::end(stringMap) )
{
++(it->second);
}
else
{
stringMap.insert( std::make_pair<char&,int>(elem, 1));
}
}
for( auto elem : stringMap)
{
if(elem.second == 1)
{
std::cout<< elem.first << "\n";
break;
}
}
}
void readInputFile( const char * fileName )
{
std::ifstream inFile( fileName, std::ifstream::in );
std::string record="tooth";
if( !inFile.is_open())
{
std::cout<<"File open failed \n";
return;
}
while( getline( inFile, record ) )
{
findNonRepeatedChar(record);
}
}
int main( int argc, char* argv[] )
{
if( argc < 2 )
{
std::cout<<"Usage:program_name input_file_name \n";
}
readInputFile(argv[1]);
}