Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#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;
}