/* * list-02.cc Standard Library, std::list, exercise 2. */ #include #include #include #include #include #include using namespace std; template struct greatest_common_divisor { T operator()(const T& a, const T& b) const { return a == 0 ? b : (*this)(b % a, a); // recursive call... } typedef T result_type; typedef T first_argument_type; typedef T second_argument_type; }; template void output_three_columns(ostream& os, int width, InputIterator first1, InputIterator last1, InputIterator first2, InputIterator first3) { while (first1 != last1) { os << setw(width) << *first1++ << setw(width) << *first2++ << setw(width) << *first3++ << '\n'; } } int main(int argc, char* argv[]) { if (argc != 2) { cout << "usage: argv[0] inputfile" << endl; return 1; } ifstream input(argv[1]); if (! input) { cout << "can not open input file " << argv[1] << '\n'; return 2; } list list1, list2, gcd_list; int x; while (input >> x) { list1.push_back(x); input >> x; list2.push_back(x); } input.close(); transform(begin(list1), end(list1), begin(list2), back_inserter(gcd_list), greatest_common_divisor()); cout << setw(8) << "First" << setw(8) << "Second" << setw(8) << "GCD\n\n"; output_three_columns(cout, 8, begin(list1), end(list1), begin(list2), begin(gcd_list)); return 0; }