#include <iostream>
#include <string>
#include <map>
#include <set>
#include <sstream>
#include <fstream>
// you may want to adjust this as appropriate for your use-case
std::string remove_punct( std::string str ) // replace punctuation with space
{
for( char& c : str ) if( !std::isalnum(c) ) c = ' ' ;
return str ;
}
std::map< std::string, std::set<int> > make_word_map( std::istream& stm )
{
std::map< std::string, std::set<int> > word_map ;
int line_number = 0 ;
std::string line ;
while( std::getline( stm, line ) ) // for each line read in from the stream
{
++line_number ; // increment the line number
// split the line into 'words'
std::istringstream str_stm( remove_punct(line) );
std::string word ;
while( str_stm >> word ) // for each 'word' in the line
word_map[word].insert(line_number) ; // insert word, line_number into the map
// not that the set will automatically discard duplicate line numbers
}
return word_map ;
}
int main()
{
std::ifstream file( __FILE__ ) ;
constauto map = make_word_map(file) ;
// for testing: print out the contents of the map
for( constauto& pair : map ) // for each key/mapped_value pair in the map
{
std::cout << pair.first << " : " ; // print the key (word)
for( int line_num : pair.second ) // for each line number in the set
std::cout << line_num << ' ' ;
std::cout << '\n' ;
}
}