#include #include #include #include #include #include // istringstream #include // for exit using namespace std; /** * read a file, print each word and line numbers * on which word occurs, words printed in alphabetical order * @author Owen Astrachan */ typedef map > linemap; // easier to use linemap in code ostream& operator <<(ostream& out,const pair >& p) // post: string/set printed all on line line { out << p.first << "\t"; set::iterator it = p.second.begin(); // print set on one line for(; it != p.second.end(); it++) { out << *it << " "; } return out; } int main(int argc, char *argv[]) { string filename,line, w; if (argc == 1) { cerr << "usage: " << argv[0] << " filename" << endl; exit(1); } filename = argv[1]; ifstream input(filename.c_str()); linemap info; int linecount = 0; while (getline(input,line)) { linecount++; istringstream iline(line); while (iline >> w) { linemap::iterator it = info.find(w); if (it == info.end()) { set si; si.insert(linecount); info.insert(make_pair(w,si)); } else { it->second.insert(linecount); } } } linemap::iterator it; for(it = info.begin(); it != info.end(); it++) { cout << *it << endl; } return 0; }