/* C++ style program use string, vector, sort(), iostream read or generate N strings optionally sort them - Bjarne Stroustrup - http://www.research.att/~bs */ #include #include #include #include #include #include using namespace std; /* command line argument handling: prog 1 - read from cin and sort prog 0 - read from cin (don't sort) prog 1 file - read from file and sort prog 0 file - read from file (don't sort) prog 1 file ofile - read from file, sort, and write to ofile prog 0 file ofile - read from file (don't sort) and write to ofile an optional 4th argument controls preallocation. */ int main(int argc, char* argv[]) { int max = 0; // by default: read from cin int res = 1000; // by default: grow incrementally bool s = true; // by default: sort char* file = 0; char* ofile = 0; switch (argc) { // s { max | file } res case 5: res = atoi(argv[4]); case 4: ofile = argv[3]; case 3: max = atoi(argv[2]); if (max == 0) file = argv[2]; case 2: s = atoi(argv[1]); break; default: cerr << "wrong number of arguments\n"; exit(1); } vector buf; buf.reserve(res); // logically redundant; for efficiency only string d; if (max) { cout << "generate " << max << endl; } else if (file) { fstream fin(file,ios::in); cout << "C++ style read of strings from " << file << endl; while(getline(fin,d)) buf.push_back(d); } else { cout << "C++ style read of strings from read cin\n"; while(getline(cin,d)) buf.push_back(d); } if (s) { cout << "sort\n"; sort(buf.begin(),buf.end()); } if (ofile) { cout << "write " << ofile << endl; fstream fout(ofile,ios::out); copy(buf.begin(),buf.end(),ostream_iterator(fout,"\n")); } }