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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| #include<iomanip>
#include<iostream>
#include<string>
typedef struct s_Movie {
friend std::ostream& operator<< (std::ostream& os, const s_Movie& movie) {
os << "title: " << std::setw(40) << std::setiosflags(std::ios::left) << movie.title
<< std::resetiosflags(std::ios::left) << " (" << movie.year << ")";
return os;
}
public:
s_Movie(): year(0) {
std::memset(title, '\0', (len + 1));
}
s_Movie(const char* new_title, unsigned short new_year) {
if (new_title == NULL) { year = 0; std::memset(title, '\0', (len + 1)); return; }
std::copy(new_title, new_title + len, title);
// or std::strncpy(title, new_title, len);
title[len] = '\0';
year = new_year;
}
s_Movie& operator= (const s_Movie& other_movie) {
std::copy(other_movie.title, other_movie.title + len, title);
// or std::strncpy(title, other_movie.title, len);
title[len] = '\0';
year = other_movie.year;
return *this;
}
private:
static const unsigned len = 40;
char title[len + 1];
unsigned short year;
} Movie;
typedef struct s_List_Movies {
friend std::ostream& operator<< (std::ostream& os, const s_List_Movies& list) {
for(unsigned short movie = 0; movie < list.nb_movies; ++movie) {
os << std::setw(2) << (movie + 1) << ": " << list.list_movies[movie] << std::endl;
}
return os;
}
public:
s_List_Movies(): list_movies(NULL), nb_movies(0), max_nb_movies(0) {}
~s_List_Movies() {
if (list_movies != NULL) {
delete[] list_movies;
}
list_movies = NULL;
max_nb_movies = nb_movies = 0;
}
void add_movie(const Movie& new_movie) {
// XXX TODO: manage case list_movies == NULL
if (nb_movies == max_nb_movies) {
reserve(nb_movies + 1);
}
list_movies[nb_movies] = new_movie;
++nb_movies;
}
void reserve(unsigned short new_max_nb_movies) {
if (new_max_nb_movies == 0) { return; }
// XXX TODO: manage case list_movies == NULL
if (new_max_nb_movies > max_nb_movies) {
Movie* tmp_list_movies = new Movie[new_max_nb_movies];
for(unsigned short movie = 0; movie < nb_movies; ++movie) {
tmp_list_movies[movie] = list_movies[movie];
}
delete[] list_movies;
list_movies = tmp_list_movies;
max_nb_movies = new_max_nb_movies;
}
}
private:
Movie* list_movies;
unsigned short nb_movies;
unsigned short max_nb_movies;
} List_Movies;
int main(int argc, char* argv[])
{
Movie a("Test", 1940);
Movie b("Test1", 1945);
Movie c("Test2", 1947);
List_Movies list;
list.reserve(3);
list.add_movie(a);
list.add_movie(b);
list.add_movie(c);
std::cout << list << std::endl;
return 0;
} |
Partager