// // // // // Lab. Calcolo II - Esempio di codice // // // // // // // // Example code: STL-based sort of data that may come from stdin. // (francesco.prelz@mi.infn.it 20060810) #include <iostream> #include <iomanip> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include <system_error> #include <cerrno> #include "measurement.h" int main(int argc, char *argv[]) { typedef measurement<double> measurement_t; typedef std::vector<measurement_t> measurement_container_t; measurement_container_t measurements; std::ifstream fread; std::istream *input=&fread; // A reference variable would do here if (argc > 1) { fread.open(argv[1],std::ios::in); if (!fread) { std::cerr << argv[0] << ": Error: Cannot read from " << argv[1] << ": " << std::system_error(errno, std::system_category()).what() << "." << std::endl; return 1; } } else input = &std::cin; // But std::cin already exists and is made // 'noncopyable' via a private operator= while (input->good()) { measurement_t meas; *input >> meas; if (input->good()) measurements.push_back(meas); } std::cout << "Successfully read " << measurements.size() << " elements." << std::endl; // Implicit template instantiation is playing here as well. sort(measurements.begin(), measurements.end()); // No way to get a const_iterator out of 'auto', but we can survive here. for(auto it=measurements.begin(); it!=measurements.end(); ++it) std::cout << *it << std::endl; // An iterator "behaves as" a pointer! return 0; }