Skip to content
Snippets Groups Projects
test_stream_iterator.cpp 2.31 KiB
Newer Older
#include <iostream>
#include <fstream> // for file streams
#include <iterator> // for stream_iterators
#include <algorithm> // for sort, unique_copy
#include <string>
#include <vector>
#include <set>
#include <chrono>
#include "timer.h"

namespace ch=std::chrono;

template<typename Stream> void close_and_clear(Stream & s){
	if(s.is_open()) s.close(); // Close the stream, if open
	s.clear(); // Clear the status flags
}

int main(){
	using data_t=std::string;
	using ifile_t=std::ifstream;
	using ofile_t=std::ofstream;
	using cont_t=std::vector<data_t>;
	using set_t=std::set<data_t>;

	std::string from,to_set,to_sort;
	std::cout << " Enter the filename to read from: ";
	std::cin>> from;

	to_set="ordered_with_set_"+from;
	to_sort="ordered_with_sort_"+from;

	ifile_t is{from}; // input file stream
	std::istream_iterator<data_t> ii {is}; // input stream iterator for file "from"
	std::istream_iterator<data_t> eos{}; // empty iterator to be used as a sentinel, i.e. end of stream

	ofile_t os{to_sort}; // output file stream, sort case
	std::ostream_iterator<data_t> oo {os,"\n"}; // output iterator for filestream

	timer tt; // start timer
	std::vector<std::string> bv{ii,eos};
	std::sort(bv.begin(),bv.end());
	std::unique_copy(bv.begin(),bv.end(),oo);

	std::cout << "Ordered with sort, and saved into: "<<to_sort;
	auto dsort=tt.print_diff(". Duration: ");
	close_and_clear<ifile_t>(is);
	close_and_clear<ofile_t>(os);

	is.open(from); // reopen the input file
	os.open(to_set);

	tt.reset(); // restart the timer
	// Here the istream_iterator and the ostream_iterator are created as unnamed objects and hopefully moved or passed by value
	std::set<std::string> bs{std::istream_iterator<std::string>{is},std::istream_iterator<std::string>{}};
	std::copy(bs.begin(),bs.end(),std::ostream_iterator<std::string>{os,"\n"});

	std::cout << "Ordered with set, and saved into: "<<to_set;
	auto dset=tt.print_diff(". Duration: ");
	std::cout << " Execution time sort: "<< ch::duration_cast<ch::milliseconds>(dsort).count()
			<< "milliseconds, set: " << ch::duration_cast<ch::milliseconds>(dset).count() << "milliseconds \n";
	std::cout << "Execution time difference, in percentage, between sort and set: "
			<< (dsort.count()/dset.count()) * 100. << std::endl;

	return !is.eof() || !os;

}