31
1 Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 38 - Complément_S7 S7 Mohammed BENJELLOUN Service d’Informatique Faculté Polytechnique de Mons [email protected] 2021-2022 et Programmation Objet Méthodologie Orientée Objet Partie 1 Complément_7 Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 39 - Complément_S7 List ou vector ? #include <list> L.push_back(i) L.push_front(i); L.pop_back(); L.pop_front(); list<int> L; #include <vector> V .push_back(i) V .push_front(i); V .pop_back(); V .pop_front(); vector<int> V; V .insert(i) V.erase(iterator position); L.clear(); V .clear(); // supprime tous les éléments STL

Méthodologie Orientée Objet

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Méthodologie Orientée Objet

1

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 38 - Complément_S7

S7

Mohammed BENJELLOUN

Service d’Informatique

Faculté Polytechnique de Mons

[email protected]

2021-2022

et Programmation Objet

Méthodologie Orientée Objet

Partie 1

Complément_7

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 39 - Complément_S7

List ou vector ?

#include <list>

L.push_back(i)

L.push_front(i);

L.pop_back();

L.pop_front();

list<int> L;

#include <vector>

V.push_back(i)

V.push_front(i);

V.pop_back();

V.pop_front();

vector<int> V;

V.insert(i)

V.erase(iterator position);

L.clear(); V.clear(); // supprime tous les éléments

STL

Page 2: Méthodologie Orientée Objet

2

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 40 - Complément_S7

// L = 5 3 9 7 2 11

L.sort( ); // L = 2 3 5 7 9 11

L.sort(cmp); // L = 11 9 7 5 3 2

// V = 5 3 9 7 2 11

V.sort( );V.sort(cmp);

// L = a A B B B d d e

L.remove(‘B’);L.remove(‘d’); // L = a A e

// V = a A B B B d d e

V.remove(‘B’);V.remove(‘d’);

// L = a A B B B d d e

L.unique(); // L = a A B d e

// V = a A B B B d d e

V.unique();

#include <list>

list<int> L;

#include <vector>

vector<int> V;

List ou vector ?

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 41 - Complément_S7

// L = 5 3 9 7 2 11

L.sort( ); // L = 2 3 5 7 9 11

L.sort(cmp); // L = 11 9 7 5 3 2

// V = 5 3 9 7 2 11

V.sort( );V.sort(cmp);

// L = a A B B B d d e

L.remove(‘B’);L.remove(‘d’); // L = a A e

V.remove(‘B’);V.remove(‘d’);

L.unique(); // L = a A B d e

// V = a A B B B d d e

V.unique();

#include <list>

list<int> L;

#include <vector>

vector<int> V;

List ou vector ?

#include < algorithm>

vector<int> V;

sort(V.begin(), V.end());

remove(V.begin(),V.end(), ‘d’);

unique(V.begin(), V.end());

Page 3: Méthodologie Orientée Objet

3

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 42 - Complément_S7

http://www.cplusplus.com/reference/algorithm/

Functions in <algorithm>

Non-modifying sequence operations: Modifying sequence operations:

Algorithmes

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 43 - Complément_S7

Algorithmesremove

#include <algorithm>#include <vector>. . .

vector<int> V1, V2;

V1 = V2= { 9, 4, 2, 8, 1, 8, 3 };Affiche_A(V1, " (1) ");

remove(V1.begin(), V1.end(), 8);Affiche_A(V1, " (2) ");

V2.erase(remove(V2.begin(), V2.end(), 8), V2.end() );Affiche_A(V2, " (3) ");. . .

(1) size = 7 Data : 9 4 2 8 1 8 3-------------(2) size = 7 Data : 9 4 2 1 3 8 3-------------(3) size = 5 Data : 9 4 2 1 3

Exécution

Pour supprimer un élément à partir de sa valeur, il faut utiliser conjointement la fonction remove() et la méthode erase() pour le conteneur vector

STL

Page 4: Méthodologie Orientée Objet

4

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 44 - Complément_S7

Algorithmesunique

#include <algorithm>#include <vector>#include <list>. . .

vector<int> V1;list<int> L1;

L1 = { 9, 9, 2, 9, 2, 2, 2, 9, 8 };V1 = { 9, 9, 2, 9, 2, 2, 2, 9, 8 };

unique(V1.begin(), V1.end());Affiche_A(V1, " (V1_U) ");L1.unique();Affiche_A(L1, " (L1_U) ");

. . .

(0) size = 9 Data : 9 9 2 9 2 2 2 9 8-------------

(V1_U) size = 9 Data : 9 2 9 2 9 8 2 9 8-------------

(L1_U) size = 6 Data : 9 2 9 2 9 8

Exécution

Supprime tous les éléments sauf le premier de

chaque groupe consécutif d’éléments équivalents

dans la plage [first,last].

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 45 - Complément_S7

Algorithmessort

sort(V.begin(), V.end()); L.sort( );

Template ?

bool Profs :: operator < (PROF P) {if (nom < P.nom) {

return true;}else {

return false;}

}

bool Etudiant::operator < (Etudiant E) {if (nom < E.nom) {

return true;}else {

return false;}

}

TP

Page 5: Méthodologie Orientée Objet

5

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 46 - Complément_S7

#include <vector>#include <list>#include <algorithm>…

void main() {list<int> L;vector<int> V;

for (int i = 1; i<10; i++) L.push_back(i);

// Adapter la taille du vecteur à la taille de la liste

V.resize(L.size());

// Copier le contenu de la liste dans le vecteur

copy(L.begin(), L.end(), // source

V.begin()); // destination

}

Algorithmescopy

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 47 - Complément_S7

#include <algorithm> // for_each#include <vector>…

void Affiche(int i) {cout << ' ' << i << ' ' << i + 1 << endl;

}

int main() {vector<int> V { 5, 10, 15 };

cout << " Utilisation de for :" << endl;for (auto TI : V )

Affiche(TI);

cout << " Utilisation de for_each:" << endl;for_each ( V.begin(), V.end(), Affiche );

return 0;}

for_eachAlgorithmes

Exécution

Utilisation de for : 5 6 10 11 15 16 Utilisation de for_each: 5 6 10 11 15 16

Applique la fonction Afficheà chacun des éléments de la plage [first , last].

STL

Page 6: Méthodologie Orientée Objet

6

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 48 - Complément_S7

L’algorithme all_of vérifie que tous les éléments d’un ensemble respectent une propriété.

Exemple : vérifier si tous les caractères d’une chaîne sont des chiffres ( isdigit ?? ).

#include <algorithm> // all_of…

void main() {

string Tel = "32474123456" ;

if ( all_of (Tel.begin(), Tel.end(), isdigit) )cout << "OK, numéro de téléphone correct." << endl;

elsecout << " Erreur, entrée invalide." << endl;

}

all_of

STL

Algorithmes

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 49 - Complément_S7

#include <algorithm> // count… void main() {

list<int> L = { 0, 1, 1, 3, 4, 4, 4, 9, 8, 9 };vector<int> V = { 0, 1, 1, 3, 4, 4, 4, 9, 8, 9 };int i = 4, j = 1, k, l;

cout << "(1) :"; for (auto E : L)

cout << E << " ";cout << endl;

k = count(V.begin(), V.end(), i); // nombre de i?

l = count(L.begin(), L.end(), j);

cout << "(V) :" << k << " de " << i << endl;cout << "(L) :" << l << " de " << j << endl;}

Algorithmescount

(1) : 0 1 1 3 4 4 4 9 8 9(V) : 3 de 4(L) : 2 de 1

Exécution

STL

Page 7: Méthodologie Orientée Objet

7

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 50 - Complément_S7

#include <algorithm>…

bool SupA10 (int value) {return value > 10;

}void main() {vector<int> V1 { 5, 15, 25, 10, 20, 40, 7 };vector<int>::iterator Iter;int result;

cout << "V1 = ( ";for (Iter = V1.begin(); Iter != V1.end(); Iter++)

cout << *Iter << " ";cout << ")" << endl;

cout << "V1 = --> ";for (auto E : V1) cout << E << " ";cout << endl;

result = count_if (V1.begin(), V1.end(), SupA10 );cout << " Le nombre d'elements de V1 > 10 est: "

<< result << "." << endl;}

Algorithmescount_if

Exécution

V1 = ( 5 15 25 10 20 40 7 )V1 =--> 5 15 25 10 20 40 7Le nombre d'elements de v1 > 10 est: 4.

Retourne le nombre d’éléments de la

plage [first,last] pour lesquels SupA10 a

la valeur true.

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 51 - Complément_S7

using namespace std;#include <string>#include <algorithm>#include <iostream>#include <vector> // ou list aussi

string Egalite(vector<int> Tab1, vector<int> Tab2) {if ( (equal(begin(Tab1), end(Tab1), begin(Tab2), end(Tab2))) )

return "Egalité";else

return "Pas Egalité";}

void main() {vector<int> Tab1 { 1, 2, 3, 4 };vector<int> Tab2 { 1, 2, 3, 4, 5 };vector<int> Tab3 { 1, 2, 3, 10 }, Tab4 ;

setlocale(LC_ALL, "fr-FR");Tab4 = Tab1 ;

cout << Egalite(Tab1, Tab2) << endl;cout << Egalite(Tab1, Tab3) << endl;cout << Egalite(Tab1, Tab4) << endl;Tab4.push_back(99);cout << Egalite(Tab1, Tab4) << endl;}

Vérifier l’égalité de deux ensembles.

Si les deux ensembles n’ont pas la même

taille, alors l’égalité est impossible. Sinon,

l’algorithme va comparer les deux

ensembles élément par élément.

Algorithmesequal

Exécution

Pas EgalitéPas EgalitéEgalitéPas Egalité

STL

Page 8: Méthodologie Orientée Objet

8

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 52 - Complément_S7

const T& max ( const T& a, const T& b )const T& min ( const T& a, const T& b )

Exemples : cout << "max(5, 2 )=" << max(5,2); // 5

Algorithmesmin & maxmin_element & max_element

cout << *min_element(v.begin(),v.end()) << endl;

cout << *max_element(t, t+10) << endl;

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 53 - Complément_S7

Rechercher la séquence d’éléments [début2, fin2] et sa position dans l’ensemble [début1,fin1]

search (Itér début1, Itér fin1, Itér début2, Itér fin2);

Exemple : search(v1.begin(), v1.end(), v2.begin(), v2.end());

find() : Trouver la position de Valeur entre début et fin. Retourne comme résultat un itérateur sur cet élément.

find (Itérateur début, Itérateur fin, const Type&Valeur);

Exemple : find(v.begin(),v.end(), 15);

Algorithmessearchfind

STL

Page 9: Méthodologie Orientée Objet

9

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 54 - Complément_S7

#include <vector>#include <algorithm>…

int main() {vector<string> V{ "V0", "V1", "V2" };vector<string>::iterator It;string St;

cout << "Un string !!?: " << St;cin >> St;

It = find(V.begin(), V.end(), St);

if (It != V.end())cout << *It << " est dans V" << endl;

elsecout << St << " n'est pas dans V" << endl;

return 0;}

Algorithmesfind

STL

// TEMPLATE FUNCTION find

template<class _InIt, class _Ty>

_InIt _Find(_InIt _First, _InIt _Last, const _Ty& _Val)

{ // find first matching _Val

_DEBUG_RANGE(_First, _Last);

for (; _First != _Last; ++_First)

if (*_First == _Val)

break;

return (_First);

}

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 55 - Complément_S7

#include <algorithm> …

void affiche(list<string> L, string S){list<string>::iterator it;cout << S ;

for (it=L.begin(); it!=L.end(); it++)cout << " " << *it;

cout << endl;

}

void main() {list<string> l;list<string>::iterator it;l.push_back("il "); l.push_back("fait "); l.push_back("beau");affiche (l, "(1)");

it = find (l.begin(), l.end(), "beau");if(it != l.end())

l.insert(it, "tres ");affiche (l, "(2)");

…}

(1) il fait beau

(2) il fait tres beau

(3) il tres beau

Exce8.7. Donner le code d’un programme qui crée une liste de string représentant la phrase ”il fait beau”, trouve la position du mot ”beau” et insère le mot ”tres” à la position précédente.

Compléter le programme pour qu’il affiche le résultat de (3)

Algorithmesfind

STL

it = find(l.begin(), l.end(), "fait");

l.erase(it);affiche (l, "(3)");

Page 10: Méthodologie Orientée Objet

10

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 56 - Complément_S7

#include <vector>#include <list>#include <iostream>#include <string>#include <algorithm>using namespace std;

void main() {vector<string> V{ "V0" , "V1" , "V2"};list<int> L{ 1, 2, 3, 4 };vector<string>::iterator itV;list<int>::iterator itL;

test(V, itV, "V1", "Vecteur");test(V, itV, "V5", "Vecteur");

test(L, itL, 10 , "List");test(L, itL, 2 , "List");}

Algorithmesfind

8.8 En utilisant l’algorithme find de STL et les templates, donnez le code de la fonction « test » pour que ce programme affiche le résultat suivant :

STL

Test VecteurV1 est dans Vecteur

Test VecteurV5 n'est pas dans Vecteur

Test List10 n'est pas dans List

Test List2 est dans List

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 57 - Complément_S7

Test VecteurV1 est dans Vecteur

Test VecteurV5 n'est pas dans Vecteur

Test List10 n'est pas dans List

Test List2 est dans List

8.8 En utilisant l’algorithme find de STL et les templates, donnez le code de la fonction « test » pour que ce programme affiche le résultat suivant :

Algorithmesfind

template <class T, class T1, class T2 >void test(T Cont, T1 It, T2 cherch, string txt) {

cout << "\n Test " << txt << endl;It = find(Cont.begin(), Cont.end(), cherch);if (It != Cont.end())

cout << *It << " est dans " << txt << endl;else

cout << cherch << " n'est pas dans " << txt << endl;

}

STL

#include <vector>#include <list>#include <iostream>#include <string>#include <algorithm>using namespace std;

void main() {vector<string> V{ "V0" , "V1" , "V2"};list<int> L{ 1, 2, 3, 4 };vector<string>::iterator itV;list<int>::iterator itL;

string St1 = "V1", St2 = "V5";test(V, itV, St1, "Vecteur");test(V, itV, St2, "Vecteur");

test(L, itL, 10 , "List");test(L, itL, 2 , "List");}

Page 11: Méthodologie Orientée Objet

11

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 58 - Complément_S7

L'algorithme find_first_of permet de retrouver le premier élément vérifiant une relation avec une valeur parmi un ensemble de valeurs données.

0 en position 0255 en position 40 en position 6255 en position 8

#include <algorithm> …

int main() {

int t[10] = { 0, 5, 3, 4, 255, 7, 0, 5, 255, 9 };// Recherche les éléments valant 0 ou 255 :

int sep[2] = { 0, 255 };int *debut = t;int *fin = t + 10, *courant;

while ((courant = find_first_of(debut, fin, sep, sep + 2)) != fin) {// Affiche la position de l'élément trouvé :

cout << *courant << " en position " << courant - t << endl;debut = courant + 1;

}

return 1;}

Algorithmesfind_first_of

Exécution

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 59 - Complément_S7

V Initial : 3 5 4 9 1 9 1..... En V :{9,1} en position 3Min Ts: 1Min It: 1Max It+2: 5V Trie : 1 1 3 4 5 9 9Pour V Trie: 5 peut etre insere de 4 a 5V Trie Replace 5 par 4 : 1 1 3 4 4 9 9

#include <vector>#include <algorithm> …

void affiche(vector<int> V, string S) {cout << S << " : ";for (int i = 0; i< V.size(); i++) cout << V[i] << " ";cout << endl;

}

void main() {int T[7] = { 3, 5, 4, 9, 1, 9, 1 };int Seq[2] = { 9, 1 }, *p;

vector<int> V(T, T + 7); // itérateuraffiche(V, "V Initial");

p = search(T, T + 7, Seq, Seq + 2);cout << "..... En V :{9,1} en position " << p - T << endl;

cout << "Min Ts: " << *min_element(V.begin(), V.end()) << endl;cout << "Min It: " << *min_element(T, T + 7) << endl;cout << "Max It+2: " << *max_element(T, T + 2) << endl;

sort (V.begin(), V.end()); affiche(V, "V Trie ");

sort(T, T + 7);cout << "Pour V Trie: 5 peut etre insere de "

<< lower_bound (T, T + 7, 5) - T << " a "<< upper_bound(T, T + 7, 5) - T << endl;

replace(V.begin(), V.end(), 5, 4);affiche(V, "V Trie Replace 5 par 4");}

Algorithmes

Exécution

STL

Page 12: Méthodologie Orientée Objet

12

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 60 - Complément_S7

#include <iostream>

#include <numeric> // pour accumulate#include <vector>#include <list>using namespace std;

void main() {int tab[5] = {3, 2, 9, 1, 4};list<int> L = { 3, 2, 9, 1, 4 };vector <int> v = { 3, 2, 9, 1, 4 };

// Calculer la somme des éléments avec 0 comme valeur initialecout << "som Tab= " << accumulate(tab, tab + 5, 0) << endl; // 19 = 3+2+9+1+4+0cout << "som V = " << accumulate(v.begin(),v.end(),0) << endl; // 19cout << "som L = " << accumulate(L.begin(),L.end(),0) << endl; // 19

cout << "mult Tab= " << accumulate(tab, tab + 5, 1,multiplies<int>()) << endl; // 216cout << "mult V = " << accumulate(v.begin(),v.end(),1,multiplies<int>()) << endl; // 216cout << "mult L = " << accumulate(L.begin(),L.end(),1,multiplies<int>()) << endl; // 216

cout << "mult Tab= " << accumulate(tab, tab + 5, 10,multiplies<int>()) << endl; // 2160cout << "mult V = " << accumulate(v.begin(),v.end(),10,multiplies<int>()) << endl; // 2160cout << "mult L = " << accumulate(L.begin(),L.end(),10,multiplies<int>()) << endl; // 2160

}

Exemple d’algorithme numérique (accumule)Exemple : calcule v[3] + (v[2] + (v[1] + (v[0] + 0))).

Exemple : calcule v[3] * (v[2] * (v[1] * (v[0] * 1))).

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 61 - Complément_S7

But : Manipulation des conteneurs Vector et List et algorithmes de la librairie STL. Optimisation et création de code générique.

Déclarer deux classes : Une classe Etudiant Une seconde classe PROF

int Id; int Id;string nom; string nom, Service;

Dans les deux classes (étudiants, enseignants), on déclarera au moins deux méthodes, l’une pour saisir et l’autre pour afficher chaque objet de la classe (Saisie() et affichage()).La manipulation des étudiants se fera en utilisant un conteneur List alors que les Profs serontrangés dans un conteneur Vector.

Ce programme doit gérer en boucle le menu suivant :

0 : Choix entre Etudiants ou Profs 1 : Saisir et Afficher une List d’Etudiants ou Vector de Profs 2 : Ajouter au début et Afficher (Etud ou Prof) 3 : Supprimer au début et Afficher (Etud ou Prof) 4 : Créer une List2 contenant uniquement les noms des Etud et Profs 5 : Quitter

On y prévoira au moins: • un constructeur par classe permettant l’incrémentation automatique de l’Id (Prof1 : Id=1, Prof2 : Id=2, … et Etud1 : Id1=1, ….).Optimisez votre code afin de permettre la réutilisation des morceaux de code.

S’il vous reste du temps:Que deviendra le programme si les classes Etudiant et PROF héritent d’une classe Personne caractérisée par : int Id et string nom.

private

TP2

TP1_Lec_Fichiers.cpp

Page 13: Méthodologie Orientée Objet

13

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 62 - Complément_S7

class PROF {private:int Id;string nom, Service;

public:void saisie();void affichage();

string getnom();PROF() {

static int ID = 0;Id = ID;ID++;

}

};

void LECture(vector <PROF> &Tab, int& N) {

string temp_N, temp_S; ifstream lecture;lecture.open("Prof.txt");if (lecture) {

lecture >> N;lecture.ignore();

for (int it = 0; it < N; it++) {PROF Prof; getline(lecture, temp_N, ';’);getline(lecture, temp_S, '\n’);Prof.Set_nom(temp_N);Prof.Set_service(temp_S);Tab.push_back(Prof); // ou insert

}lecture.close();

}else

cout << "Le fichier Prof n'existe pas." << endl;}

TP2

void Set_nom(string temp) {nom = temp;}void Set_service(string temp) {Service = temp;}

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 63 - Complément_S7

class PROF {private:int Id;string nom, Service;

public:void saisie();void affichage();void Lec(ifstream &a);string getnom();PROF() {

static int ID = 0;Id = ID;ID++;

}

};

TP2 template <class T, class A> void Lecture( T &V, string f ) {int N;ifstream lecture;lecture.open(f);if (lecture) {

lecture >> N;lecture.ignore();for (int i = 0; i < N; i++) {

A temp;temp.Lec(lecture);V.push_back(temp); // ou insert

}lecture.close();

}else

cout << "Le fichier n'existe pas." << endl;}

void PROF::Lec(ifstream &a) {getline(a, nom, ';’);getline(a, Service);

}

Page 14: Méthodologie Orientée Objet

14

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 64 - Complément_S7

void CopierNom(list<Etudiant> list1, vector<Prof> vect, list<string>& list2) {

list<Etudiant>::iterator it1;

vector<Prof>::iterator it2;

list<string>::iterator it3;

for (it1 = list1.begin(); it1 != list1.end(); it1++) ;

list2.push_back(it1->get_nom());

for (it2 = vect.begin(); it2 != vect.end(); it2++) ;

list2.push_back(it2->get_nom());

for (it3 = list2.begin(); it3 != list2.end(); it3++)

; cout << *it3 << endl;

}

template <class T> ;Pas bien de copier

void CopierNomT (T Cont, list <string> &liste2) {

; typename T::iterator it2;

for (it2 = Cont.begin(); it2 != Cont.end(); it2++)

liste2.push_back(it2->get_nom());

}

Créer une List2 contenant uniquement les noms des Etud et Profs TP2

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 65 - Complément_S7

TP3

Ensuite, implémentez un programme qui doit gérer en boucle le Menu suivant :

1 : Saisie et/ou Ajout Etudiants et affichage ;2 : Saisie et/ou Ajout Profs et affichage ;3 : Supprimer un Etudiant ou un Prof à la position P ;4 : Doyen membre de Direction Calcule la Moyenne de chaque étudiant + Affichage;5 : Chercher si 1 Element (Etud ou Prof) existe ;6 : Trier selon NOM par ordre croissant et Afficher (Etud ou Prof) ;7 : Afficher la liste des étudiants par année scolaire (An_Scol) et par ordre

décroissant de leur moyenne.

Page 15: Méthodologie Orientée Objet

15

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 66 - Complément_S7

void Personne :: saisie() {cout<<" \nEntrez son nom : ";cin.ignore(); // Pour ignorer un éventuel "Enter"

getline(cin,Nom);//cout<<" \nEntrez son Id : ";//cin>>Id;cout<<"\n"<<endl;

}

void PROF :: saisie() {Personne :: saisie();cout<<" Entrez le nom du Service : ";cin>>Service;cout<<" \n";

}

void Direction :: saisie() {PROF :: saisie(); cout<<" Entrez le nom du Titre : ";cin>>Titre;cout<<" \n";

}

TP3Personneint Id ;string nom;

public :void saisie();void afficher();

Etudiant

string An_Scol ;int Note[3];

public :void saisie();void afficher() ;

Prof

string Service;public :

void saisie();void afficher();

Direction

string Titre;

public :void saisie();void afficher();..

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 67 - Complément_S7

Personneint Id ;string nom;

public :void saisie();void afficher();

Etudiant

string An_Scol ;int Note[3];

public :void saisie();void afficher() ;

Prof

string Service;public :

void saisie();void afficher();

Direction

string Titre;

public :void saisie();void afficher();..

class Personne {int Id;string Nom;

public:void saisie();void afficher();string getNom();int ReturnId();

};

class Etudiant : public Personne {string anne_scol;int Note[Note_Max];

public:void saisie();void afficher();string get_an() ; int getNote(int i) {

return Notes[i]; }

};

class Direction;

friend Direction;

4 : Doyen membre de Direction Calcule la Moyenne de chaque étudiant5 : Chercher si 1 Element (Etud ou Prof) existe ;6 : Trier selon NOM par ordre croissant et Afficher (Etud ou Prof) ;

bool operator < (Personne P) {return nom < P.nom ; }

TP3

Page 16: Méthodologie Orientée Objet

16

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 68 - Complément_S7

Personneint Id ;string nom;

public :void saisie();void afficher();

Etudiant

string An_Scol ;int Note[3];

public :void saisie();void afficher() ;

Prof

string Service;public :

void saisie();void afficher();

Direction

string Titre;

public :void saisie();void afficher();..

class Direction : public PROF {

…public:

...float moyenne(Etudiant E) {

float moyenne = 0;for(int i = 0 ; i < Note_Max; i++)

moyenne += E.Note[i];

return moyenne/Note_Max;}

...};

4 : Doyen membre de Direction Calcule la Moyenne de chaque étudiant5 : Chercher si 1 Element (Etud ou Prof) existe ;6 : Trier selon NOM par ordre croissant et Afficher (Etud ou Prof) ;

TP3

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 69 - Complément_S7

Personneint Id ;string nom;

public :void saisie();void afficher();

Etudiant

string An_Scol ;int Note[3];

public :void saisie();void afficher() ;

Prof

string Service;public :

void saisie();void afficher();

Direction

string Titre;

public :void saisie();void afficher();..

4 : Doyen membre de Direction Calcule la Moyenne de chaque étudiant5 : Chercher si 1 Element (Etud ou Prof) existe ;6 : Trier selon NOM par ordre croissant et Afficher (Etud ou Prof) ;

class Personne {...public:

bool operator == (Personne p) {if (nom == p.nom) return true;else return false;

}...

};

…cout << "Quel element recherchez-vous ?" << endl;temp.saisie();it = find(tab.begin(), tab.end(), temp);

TP3

Page 17: Méthodologie Orientée Objet

17

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 70 - Complément_S7

void tri (list<Etudiant> &list1){

list<Etudiant>::iterator it1, it2;

Etudiant tmp;

int Drap=1 ;

it2=list1.begin();

it1=list1.begin();

it1++;

if((*it1).GetNom ()>(*it2).GetNom ()){

tmp=(*it2);

(*it2)=(*it1);

(*it1)=tmp;

Drap=1;

}

}

void trinom(vector<PROF> &Pr, int N) {

int Drap=1;

PROF temp;

while(perm==1){

perm=0;

for(int i=0;i<N-1;i++){

if(Pr[i].GetNom ()>Pr[i+1].GetNom()){

temp=Pr[i];

Pr[i]=Pr[i+1];

Pr[i+1]=temp;

perm=1;

}

}

}

}

STL

Trier selon NOM par ordre croissantChercher si 1 Element (Etud ou Prof) existe ;

int PROF::operator > (PROF P) {if(nom>P.nom) return 1;else return 0;

}int PROF::operator >>(PROF P) {

if( Id>P.Id ) return 1;else return 0;

}

TRI(1)

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 71 - Complément_S7

bool Profs :: operator < (PROF P) {if (nom < P.nom) {

return true;}else {

return false;}

}

bool Etudiant::operator < (Etudiant E) {if (nom < E.nom) {

return true;}else {

return false;}

}

bool Personne::operator < (Personne P) {return nom < P.nom ;

}

// sens du TRI croissant selon nom

TRI(2)list< Etudiant > Etuds, L; vector<PROF> Profs, V;

bool Personne::operator < (Personne P) {if (nom < P.nom) {

return true;}else {

return false;}

}

L.sort();

L.sort(cmp);

V.sort();

V.sort(cmp);

sort ( V.begin(), V.end());

sort ( V.begin(), V.end(), cmp );

Page 18: Méthodologie Orientée Objet

18

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 72 - Complément_S7

bool Personne::operator < (Personne P) {return nom < P.nom ;

}

// sens du TRI croissant

TRI(3)

bool Personne::operator < (Personne P) {if (nom < P.nom) {

return true;}else {

return false;}

}

list< Etudiant > Etuds; vector<PROF> Profs;

Etuds.sort( ); Affichage(Etuds);

sort(Profs.begin(), Profs.end() ); Affichage(Profs);

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 73 - Complément_S7

TRI(4)list< Etudiant > Etuds; vector<PROF> Profs;

4 : Doyen membre de Direction Calcule la Moyenne de chaque étudiant5 : Chercher si 1 Element (Etud ou Prof) existe ;6 : Trier selon NOM par ordre croissant et Afficher (Etud ou Prof) ;

case 5:...if (choix1 == 'E' || choix1 == 'e') {

Etuds.sort();affichage(Etuds);

}if (choix1 == 'P' || choix1 == 'p') {

sort(Profs.begin(), Profs.end());affichage(Profs);

}break;

Etuds.sort( ); Affichage(Etuds);

sort(Profs.begin(), Profs.end() ); Affichage(Profs);

// sens du TRI croissant

Page 19: Méthodologie Orientée Objet

19

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 74 - Complément_S7

TRI(5)list< Etudiant > Etuds; vector<PROF> Profs;

4 : Doyen membre de Direction Calcule la Moyenne de chaque étudiant5 : Chercher si 1 Element (Etud ou Prof) existe ;6 : Trier selon NOM par ordre croissant et Afficher (Etud ou Prof) ;

Etuds.sort( CMP ); Affichage(Etuds);

bool CMP ( Etudiant a, Etudiant b) {direction D;return ( (a.get_an() <= b.get_an()) && ( D.moyenne(a) < D.moyenne(b) ) );

}

// sens du TRI décroissant

nom? & id ? & moyenne ? !

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 75 - Complément_S7

bool compare_etud (Etudiant A, Etudiant B){

if (A.Get_Id() > B.Get_Id())return true;

elsereturn false;

}

Etuds.sort(compare_etud); Affichage(Etuds);

bool compare_prof(PROF A, PROF B) {Pas bien de copierif (A.Get_Id() > B.Get_Id())

return true; else

return false; }

sort(Profs.begin(), Profs.end(),compare_prof); Affichage(Profs);

// sens du TRI décroissant

list< Etudiant > Etuds; vector<PROF> Profs; TRITRI(6)

Page 20: Méthodologie Orientée Objet

20

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 76 - Complément_S7

bool compare_etud (Etudiant A, Etudiant B){

if (A.Get_Id() > B.Get_Id())return true;

elsereturn false;

}

bool compare_prof(PROF A, PROF B) {if (A.Get_Id() > B.Get_Id())

return true; else

return false; }

list< Etudiant > Etuds; vector<PROF> Profs; TRI

template <class T>bool compId(T e1, T e2) {

if(e1. Get_Id() > e2. Get_Id() ) return true;

elsereturn false;

}

template <class T> bool compId(T e1, T e2) { return (e1. Get_Id() > e2. Get_Id() );

}

// sens du TRI décroissant

TRI(7)

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 77 - Complément_S7

template <class T> bool compId(T e1, T e2) { if(e1. Get_Id() > e2. Get_Id() )

return true; else

return false; }

Etuds.sort(compId<Etudiant>);

sort(Profs.begin(), Profs.end(), compId<PROF>);

template <class T> bool compId(T e1, T e2) { return (e1. Get_Id() > e2. Get_Id() );

}

list< Etudiant > Etuds; vector<PROF> Profs; TRI

// sens du TRI décroissant

TRI(8)

Page 21: Méthodologie Orientée Objet

21

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 78 - Complément_S7

Conteneuriterator begin()iterator end()

bool empty…

Séquence

vector list deque

Associatif

map multimap set multiset

Paramétrés par la clé et la valeur Paramétrés par la clé

set <K,Cmp > map <K,V,Cmp >

ObelixTintinAsterixTiteufTiteufObelixAsterixTiteuf

AsterixAsterixObelixObelixTintinTiteufTiteufTiteuf

AsterixObelixTintinTiteuf

Le tableau associatif

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 79 - Complément_S7

Conteneuriterator begin()iterator end()

bool empty…

Séquence

vector list deque

Associatif

map multimap set multiset

Paramétrés par la clé et la valeur Paramétrés par la clé

Le tableau associatif

A partir de la clé, on accède à la valeur associée Ils sont particulièrement adaptés lorsqu'on a besoin de réaliser un grand

nombre d'opérations de recherche.

Page 22: Méthodologie Orientée Objet

22

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 80 - Complément_S7

On trouve quatre conteneurs associatifs (ensembles ordonnées)

• set <KClé, Cmp > ; map <KClé, Vvaleur, Cmp >

Cmp = fonction qui définit la comparaison entre deux clés.

Croissant par défaut ( set <K > ; map <K, V > ).

Le tableau associatif

map est implémenté à base d'arbres binaires équilibrés.

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 81 - Complément_S7

On trouve quatre conteneurs associatifs (ensembles ordonnées)

• set <KClé, Cmp > ; map <KClé, Vvaleur, Cmp >

Cmp = fonction qui définit la comparaison entre deux clés.

Croissant par défaut ( set <K > ; map <K, V > ).

Le tableau associatif

map est implémenté à base d'arbres binaires équilibrés.

STL

Page 23: Méthodologie Orientée Objet

23

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 82 - Complément_S7

Insertion Suppression Accès Recherche

par valeurtête qcq queue tête qcq queue tête qcq queue

vector (n) (n) (1) (n) (n) (1) (1) (n)

list (1) (1) (1) (n) (1) (n)

set/map

- (log n) - - (log n) - (1) - (1) (log n)

complexité

Le tableau associatif

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 83 - Complément_S7

Headers <set> <map>

Members set multiset map multimap

constructor set multiset map multimap

destructor ~set ~multiset ~map ~multimap

assignment operator= operator= operator= operator=

iterators

begin begin begin begin begin

end end end end end

rbegin rbegin rbegin rbegin rbegin

rend rend rend rend rend

const

iterators

cbegin cbegin cbegin cbegin cbegin

cend cend cend cend cend

crbegin crbegin crbegin crbegin crbegin

crend crend crend crend crend

capacity

size size size size size

max_size max_size max_size max_size max_size

empty empty empty empty empty

reserve

element access

at at

operator[] operator[]

modifiers

emplace emplace emplace emplace emplace

emplace_hint emplace_hint emplace_hint emplace_hint emplace_hint

insert insert insert insert insert

erase erase erase erase erase

clear clear clear clear clear

swap swap swap swap swap

Operations

count count count count count

find find find find find

equal_range equal_range equal_range equal_range equal_range

lower_bound lower_bound lower_bound lower_bound lower_bound

upper_bound upper_bound upper_bound upper_bound upper_bound

observers

get_allocator get_allocator get_allocator get_allocator get_allocator

key_comp key_comp key_comp key_comp key_comp

value_comp value_comp value_comp value_comp value_comp

STL

Page 24: Méthodologie Orientée Objet

24

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 84 - Complément_S7

(constructor)

(destructor)

operator=

Iterators:

begin

end

rbegin

rend

cbegin

cend

crbegin

crend

Capacity:

empty

size

max_size

Construct map

Map destructor

Copy container content

Return iterator to beginning

Return iterator to end

Return reverse iterator to reverse beginning

Return reverse iterator to reverse end

Return const_iterator to beginning

Return const_iterator to end

Return const_reverse_iterator to reverse beginning

Return const_reverse_iterator to reverse end

Test whether container is empty

Return container size

Return maximum size

Element access:

operator[] at

Modifiers:

insert

erase

swap

clear

emplacemplace_hint

Observers:

key_compvalue_comp

Operations:

findcount

lower_boundupper_bound

equal_range

Access elementAccess element

Insert elements

Erase elements

Swap content

Clear content

Construct and insert elementConstruct and insert element with hint

Return key comparison objectReturn value comparison object

Get iterator to elementCount elements with a specific key

Return iterator to lower boundReturn iterator to upper bound

Get range of equal elementsReturns an iterator that addresses thelocation succeeding the last element in a map.

Template Class public Member Functions

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 85 - Complément_S7

Heros.insert("Tintin");

#include <iostream>#include <string>

#include <set>using namespace std;

void main() {set<string> Heros;set<string>::iterator H;set<int> Nbre;set<int>::iterator it;

for (H= Heros.begin(); H != Heros.end(); H++)cout<< *H << endl;

Nbre.insert(9); Nbre.insert(3); Nbre.insert(6);

for (it= Nbre.begin(); it != Nbre.end(); it++)cout<< *it << endl;}

Affichage :

Tintin

Heros.insert("Asterix");AsterixHeros.insert("Obelix");ObelixHeros.insert("Asterix");

Heros.insert("Titeuf");TiteufHeros.insert("Obelix");

369

Le tableau associatifSet

// set <K >

Page 25: Méthodologie Orientée Objet

25

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 86 - Complément_S7

#include <iostream>#include <string>

#include <set>using namespace std;

void main() {set<string> Heros;set<string>::iterator H;set<int> Nbre;set<int>::iterator it;Heros.insert("Tintin");Heros.insert("Asterix");Heros.insert("Obelix");Heros.insert("Asterix");Heros.insert("Titeuf");Heros.insert("Obelix");

for (H= Heros.begin(); H != Heros.end(); H++)cout<< *H << endl;

Nbre.insert(9); Nbre.insert(3); Nbre.insert(6);

for (it= Nbre.begin(); it != Nbre.end(); it++)cout<< *it << endl;

}

Set

Affichage :

AsterixObelixTintinTiteuf369

Le tableau associatif

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 87 - Complément_S7

#include <iostream>#include <string>

#include <set>using namespace std;

void main() {multiset<string> Heros;multiset<string>::iterator H;set<int> Nbre;set<int>::iterator it;Heros.insert("Tintin");Heros.insert("Asterix");Heros.insert("Obelix");Heros.insert("Asterix");Heros.insert("Titeuf");Heros.insert("Obelix");

for (H= Heros.begin(); H != Heros.end(); H++)cout<< *H << endl;

Nbre.insert(9); Nbre.insert(3); Nbre.insert(6);

for (it= Nbre.begin(); it != Nbre.end(); it++)cout<< *it << endl;

}

Affichage :

AsterixAsterixObelixObelixTintinTiteuf369

Le tableau associatifMultiSet

Page 26: Méthodologie Orientée Objet

26

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 88 - Complément_S7

#include <iostream>#include <string>#include <set>using namespace std;

void main() {multiset<string> Heros;multiset<string>::iterator H;

setlocale(LC_ALL,"");

Heros.insert("Tintin");Heros.insert("Asterix");Heros.insert("Obelix");Heros.insert("Asterix");Heros.insert("Titeuf");Heros.insert("Obelix");

for (H= Heros.begin(); H != Heros.end(); H++)cout<< *H << endl;

if (Heros.find("Obelix") != Heros.end()) cout << "Obelix est là" << endl;

cout << "Nombre de ‘Asterix’ : " << Heros.count("Asterix") << endl;cout << "Nombre de ‘Titeuf’ : " << Heros.count("Titeuf") << endl;

Heros.clear();

if (Heros.empty()) cout << "L’ensemble est vidé" << endl;else cout << "MultiMap n'est pas vide" << endl;

}

Affichage :

AsterixAsterixObelixObelixTintinTiteuf

Obelix est là

Nombre de 'Asterix' : 2Nombre de 'Titeuf' : 1

L'ensemble est vidé

Le tableau associatifMultiSet

STL

Si Obelix existe alors afficher "Obelix est là"

Calculer le nombre d’Asterix et de Titeuf

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 89 - Complément_S7

#include <iostream>#include <string>

#include <map>using namespace std;

void main() {map<string, float> poids; // table qui associe le nom d'un animal à son poids

map<string, float>::iterator it;

//On ajoute les poids de quelques animauxpoids["souris"] = 0.05;poids["tigre"] = 200;poids["chat"] = 3;poids["elephant"] = 10000;

for(it=poids.begin(); it!=poids.end(); it++) cout << it->first << " pese " << it->second << " kg." << endl;

}

MapLe tableau associatif

Affichage :

chat pese 3 kg.elephant pese 10000 kg.souris pese 0.05 kg.tigre pese 200 kg.

STL

Dans une map, les objets stockés sont des ‘pair’. Pour chaque paire, l'attribut first correspond à la clé alors que second est la valeur.

// map <K, V >

Page 27: Méthodologie Orientée Objet

27

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 90 - Complément_S7

#include <iostream>#include <string>

#include <map>using namespace std;

void main() {map<string, float> poids; // table qui associe le nom d'un animal à son poids

//On ajoute les poids de quelques animaux

poids["souris"] = 0.05;poids["tigre"] = 200;poids["chat"] = 3;poids["elephant"] = 10000;

for (auto E : poids)cout << E.first << " pese " << E.second << " kg." << endl;

}

MapLe tableau associatif

STL

Dans une map, les objets stockés sont des ‘pair’. Pour chaque paire, l'attribut first correspond à la clé alors que second est la valeur.

Affichage :

chat pese 3 kg.elephant pese 10000 kg.souris pese 0.05 kg.tigre pese 200 kg.

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 91 - Complément_S7

#include <map>…

template <class A> void Affichage(A Tab, string S) {typename A::iterator it;cout << S << " dans Affichage :" << endl;for(it=Tab.begin(); it!=Tab.end(); it++)

cout<< S<<"[" << it->first << "]=" << it->second<< " et \n"; // ou (*it)->first}

void main() {

map<string,int> M; // Pour chaque clé correspondra une seule valeur associée.

M["Tintin"] = 2;M.insert(make_pair("Asterix",5));M.insert(make_pair("Obelix",9));M.insert(make_pair("Obelix",9));M.insert(make_pair("Obelix",7));

Affichage(M, " M");

cout<< "Affichage hors boucle : " << endl;cout<< "M[Obelix] : " << M["Obelix"] << " et \n";cout<< "M[Tintin] : " << M["Tintin"] << endl;

}

Affichage :

M dans Affichage :

M[Asterix]=5 et

M[Obelix]=9 et

M[Tintin]=2 et

Affichage hors boucle :

M[Obelix] : 9 et

M[Tintin] : 2

Le tableau associatifMap

STL

Page 28: Méthodologie Orientée Objet

28

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 92 - Complément_S7

#include <map>…

template <class A> void Affichage(A Tab, string S) {typename A::iterator it;cout << S << " dans Affichage :" << endl;for(it=Tab.begin(); it!=Tab.end(); it++) cout<< S<<"[" << it->first << "]=" << it->second<< " et \n"; // ou (*it)->first

}

void main() {

map<string,int> M; // Pour chaque clé correspondra une seule valeur associée.

M["Tintin"] = 2;M.insert(make_pair("Asterix",5));M.insert(make_pair("Obelix",9));M.insert(make_pair("Obelix",9));M.insert(make_pair("Obelix",7));

Affichage(M, " M");

cout<< "Affichage hors boucle : " << endl;cout<< "M[Obelix] : " << M["Obelix"] << " et \n";cout<< "M[Tintin] : " << M["Tintin"] << endl;

}

Le tableau associatifMap

M["Obelix"] = 1;

STL

Affichage :

M dans Affichage :

M[Asterix]=5 et

M[Obelix]=9 et

M[Tintin]=2 et

Affichage hors boucle :

M[Obelix] : 9 et

M[Tintin] : 2

1

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 93 - Complément_S7

#include <map>…

template <class A> void Affichage(A Tab, string S) {typename A::iterator it;cout << S << " dans Affichage :" << endl;for(it=Tab.begin(); it!=Tab.end(); it++) cout<< S<<"[" << it->first << "]=" << it->second<< " et \n"; // ou (*it)->first

}

void main() {

multimap<string,int> M; // Pour chaque clé correspondra une seule valeur associée.

M["Tintin"] = 2;M.insert(make_pair("Asterix",5));M.insert(make_pair("Obelix",9));M.insert(make_pair("Obelix",9));M.insert(make_pair("Obelix",7));

Affichage(M, " M");

cout<< "Affichage hors boucle : " << endl;cout<< "M[Obelix] : " << M["Obelix"] << " et \n";cout<< "M[Tintin] : " << M["Tintin"] << endl;

}

Le tableau associatifMap

M["Obelix"] = 1;

// error C2676: '[' binaire : 'std::multimap<_Kty,_Ty>' ne définit pas cet opérateur

STL

Affichage :

M dans Affichage :

M[Asterix] = 5 et

M[Obelix] = 9 et

M[Obelix] = 9 et

M[Obelix] = 7 et

Page 29: Méthodologie Orientée Objet

29

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 94 - Complément_S7

#include ...

template <class A> void Affichage(A Tab, string S) {

. . .}

void main() { map <string,string> GSM; map <string,string>:: iterator G;

GSM.insert(make_pair("Asterix","474222222"));GSM.insert(make_pair("Obelix","475333333"));GSM["Tintin"] = "476444444";

Affichage(GSM, "GSM");

G = GSM.find("Obelix"); //renvoie end si n’exite pasif(G == GSM.end())cout << "Obelix n'existe pas !!" << endl;

elseGSM.erase(G);

cout<< "\n GSM[i] apres suppression? : " << endl;Affichage(GSM, "GSM");}

Affichage :

GSM dans Affichage :GSM[Asterix]=474222222 et GSM[Obelix]=475333333 et GSM[Tintin]=476444444 et

GSM[i] apres suppression? :GSM dans Affichage :GSM[Asterix]=474222222 et GSM[Tintin]=476444444 et

Le tableau associatifMap

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 95 - Complément_S7

#include ...

struct Etud {int id;string name;

};

void main() {

map<int, Etud> Stud;map<int, Etud>::iterator it;

Stud[124].id = 1;Stud[124].name = " Obelix";

Stud[12].id = 5;Stud[12].name = " Asterix";

Stud[120].id = 7;Stud[120].name = " Tintin";

Stud[12].id = 9;Stud[12].name = " Ass_TRix"; // écrase ancien Stud[12]

for(it=Stud.begin(); it!=Stud.end(); it++ ) cout<< it->first << " " << it->second.id << " " << it->second.name << endl;

}

Le tableau associatifMap

STL

Affichage :

124 1 Obelix

12 5 Asterix

120 7 Tintin

12 9 Ass_TRix

Page 30: Méthodologie Orientée Objet

30

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 96 - Complément_S7

#include ...struct Etud {

int id;string name;

};

void main() {multimap<int, Etud> Stud;multimap<int, Etud>::iterator it;int static K = 1 ;

for (int i = 0; i < 3; i++) {Etud E;E.id = i + 1; // id = 1E.name = "Stud" + to_string( K ); // Stud1Stud.insert(make_pair(i, E)); // 0 1 Stud1K++;

}

cout << "Affichage 1" << endl;for (auto St:Stud)

cout << St.first << " " << St.second.id << " " << St.second.name << endl;

cout << "Affichage 2" << endl;for (it = Stud.begin(); it != Stud.end() ; it++)

cout << it->first << " " << it->second.id << " " << it->second.name << endl;}

Affichage 1

0 1 Stud1

1 2 Stud2

2 3 Stud3

Affichage 2

0 1 Stud1

1 2 Stud2

2 3 Stud3

MultiMapLe tableau associatif

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 97 - Complément_S7

#include ...struct Etud {

int id;string name;

};

void main() {multimap<int, Etud> Stud;multimap<int, Etud>::iterator it;int static K = 1 ;

for (int j = 0; j < 3; j++)

for (int i = 0; i < 3; i++) {Etud E;E.id = i + 1; // id = 1E.name = "Stud" + to_string( K ); // Stud1Stud.insert(make_pair(i, E)); // 0 1 Stud1K++;

}

cout << "Affichage 1" << endl;for (auto St:Stud)

cout << St.first << " " << St.second.id << " " << St.second.name << endl;

}

MultiMapLe tableau associatif

STL

Affichage 1

0 1 Stud10 1 Stud40 1 Stud71 2 Stud21 2 Stud51 2 Stud82 3 Stud32 3 Stud62 3 Stud9

Page 31: Méthodologie Orientée Objet

31

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 98 - Complément_S7

Formidable , fooormidable Tu étais formidable, j'étais fort minable Nous étions formidables

FormidableTu étais formidable, j'étais fort minableNous étions formidables

Eh le bébé, oups : mademoiselleJe vais pas vous draguer, promis, juréJ'suis célibataire et depuis hier putainJ'peux pas faire l'enfant mais bon c'est pas... eh revient !5 minutes quoi j't'ai pas insulté, j'suis poli, courtoisEt un peu fort bourré et pour les mecs comme moiVous avez autre chose à faire, vous m'auriez vu hierOù j'étais

Formidable , fooormidableTu étais formidable, j'étais fort minableNous étions formidablesFormidable…

Exemple :Déterminer le nombre d’occurrence des mots 'Formidable’ ;'formidable’ ; 'formidables’ et 'fooormidable'

STL

Université de Mons 2021-2022- M. Benjelloun M.O.O._P1 - 99 - Complément_S7

#include <iostream>#include <map>#include <string>#include <fstream>using namespace std;

void main() {

map<string, int> occurrences;string mot;

ifstream read("texte.txt");

while (read >> mot) { //On lit le fichier mot par mot++occurrences[mot]; //On incrémente le compteur pour le mot lu

}cout << "Le mot 'Formidable' est present " << occurrences["Formidable"]

<< " fois dans le fichier" << endl;

cout << "Le mot 'formidable' est present " << occurrences["formidable"] << " fois dans le fichier" << endl;

cout << "Le mot 'formidables' est present " << occurrences["formidables"] << " fois dans le fichier" << endl;

cout << "Le mot 'fooormidable' est present " << occurrences["fooormidable"] << " fois dans le fichier" << endl;

system("pause");}

Le mot 'Formidable' est present 4 fois dans le fichierLe mot 'formidable' est present 0 fois dans le fichierLe mot 'formidables' est present 3 fois dans le fichierLe mot 'fooormidable' est present 2 fois dans le fichier

Appuyez sur une touche pour continuer...

ifstream read;string file;cout<<" Entrez le nom du fichier "<<endl;cin>>file;read.open(file);if(read) {while( ! read.eof()) { read >> mot ; …

STL