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
|
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <fstream>
struct cd {
std::string title ;
double price = 0 ;
int year = 0 ;
// compare two cds with the < operator; compare (case-sensitive) titles
friend bool operator< ( const cd& a, const cd& b ) {
return a.title < b.title ;
}
friend std::ostream& operator<< ( std::ostream& stm, const cd& c ) {
return stm << "cd{ " << c.title << ", "
<< c.price << ", " << c.year << " }" ;
}
};
struct cd_collection {
std::list<cd> cd_list ;
std::ostream& print( std::ostream& stm = std::cout ) const {
for( const cd& c : cd_list ) stm << c << '\n' ;
return stm ;
}
void insert_sorted( const cd& this_cd ) {
// get an iterator to the first element in cd_list that is greater than this_cd
// https://en.cppreference.com/w/cpp/algorithm/upper_bound
const auto where = std::upper_bound( cd_list.begin(), cd_list.end(), this_cd ) ;
// insert this_cd at that position
cd_list.insert( where, this_cd ) ;
}
};
int main() {
cd_collection coll ;
coll.insert_sorted( { "ijkl", 2.4, 2007 } ) ;
coll.insert_sorted( { "abcd", 5.6, 2117 } ) ;
coll.insert_sorted( { "mnop", 8.2, 2110 } ) ;
coll.insert_sorted( { "efgh", 1.5, 2019 } ) ;
coll.insert_sorted( { "qrst", 3.8, 2001 } ) ;
coll.print() ; // print to stdout
// print to file
std::ofstream file { "my_cds.txt" } ;
coll.print(file) ;
}
|