forked from benoitlecallennec-hes/template_slides_course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09_Bibliotheque_standard.html
More file actions
1329 lines (1176 loc) · 50.8 KB
/
Copy path09_Bibliotheque_standard.html
File metadata and controls
1329 lines (1176 loc) · 50.8 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>HE-Arc - 1242.2 Langage C++ - Chapitre 9 - Bibliothèque standard</title>
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css">
<link rel="stylesheet" href="dist/theme/hearc.css" id="theme">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="https://www.he-arc.ch/wp-content/uploads/2021/12/cropped-hearc-icon-192x192.png"
type="image/vnd.microsoft.icon" />
<!-- Theme used for syntax highlighted code -->
<link rel="stylesheet" href="plugin/highlight/vs.css" id="highlight-theme">
</head>
<body>
<img id="logo-hearc" src="./medias/logo_he-arc.png" alt="Logo HE-ARC">
<img id="logo-hesso" src="./medias/logo_hes-so.png" alt="Logo HES-SO">
<p id="course-infos">1242.2 Langage C++ - 2025-2026</p>
<div class="reveal">
<div class="slides">
<!---------- TITLE ---------->
<section>
<h1>
Chapitre 9
</h1>
<h2>
Bibliothèque standard
</h2>
<div class="container">
<div class="col-left">
<p>1. Vue d'ensemble</p>
<p>2. Flux et fichiers</p>
<p>3. Flux et <inline-code>
<highlight>std::string</highlight>
</inline-code></p>
<p>4. Conteneurs séquentiels</p>
</div>
<div class="col-right">
<p>5. Itérateurs</p>
<p>6. Conteneurs associatifs</p>
<p>7. Smart pointers</p>
</p>
</div>
</div>
</section>
<!---------- 9.1 Vue d'ensemble ---------->
<section>
<section>
<h2>9.1 Vue d'ensemble</h2>
<p>Ensemble de classes et de fonctions qui fournissent des fonctionnalités courantes</p>
<p>Divisée en plusieurs parties, chacune ayant un but spécifique</p>
<p>Définie dans le namespace <inline-code>
<highlight>std</highlight>
</inline-code></p>
<p>Incluse par défaut dans la plupart des compilateurs C++ modernes</p>
<p>Plus de 50 fichiers d'en-tête : <inline-code>
<highlight>iostream</highlight>
</inline-code>, <inline-code>
<highlight>vector</highlight>
</inline-code>, <inline-code>
<highlight>list</highlight>
</inline-code>, <inline-code>
<highlight>string</highlight>
</inline-code>, ...</p>
<h3>En particulier</h3>
<p>- La bibliothèque standard C</p>
<p>- Gestion des exceptions</p>
<p>- Gestion des flux</p>
<p>- Gestion des chaînes de caractères</p>
<p>- La bibliothèque standard template library (STL)</p>
<p>- Des codes éprouvés (algorithmes, ...)</p>
</section>
</section>
<!------------ 9.2 Flux et fichiers ---------->
<section>
<section>
<h2>9.2 Flux et fichiers</h2>
<p>Un flux est une séquence d'octets transférés entre la mémoire et les périphériques</p>
<p>C'est le programme qui donne une signification aux octets d'un flux</p>
<p>Les flux fournissent une méthode unifiée pour traiter les E/S quels que soient les périphériques et les
types de données à échanger</p>
<p>Classes implémentant des flux :</p>
<p>- <inline-code>
<highlight>iostream</highlight>
</inline-code> : flux standard d'E/S (clavier / écran)</p>
<p>- <inline-code>
<highlight>fstream</highlight>
</inline-code> : flux d'E/S dans les fichiers</p>
<p>- <inline-code>
<highlight>sstream</highlight>
</inline-code> : flux d'E/S dans la mémoire (string)</p>
<p>- ...</p>
<br>
<!-- NOTE: we use html code here because auto-formating with << breaks the code -->
<p>Toutes ces classes redéfinissent les opérateurs <inline-code>
<highlight><<</highlight>
</inline-code> et <inline-code>
<highlight>>></highlight>
</inline-code>
</section>
<section>
<h2>9.2 Les fichiers</h2>
<p>2 types de fichiers : texte (par défaut) ou binaire</p>
<p>2 modes d'accès : séquentiel ou direct (random access)</p>
<p><inline-code>
<highlight>#include <fstream></highlight>
</inline-code> ⇒ 3 classes :</p>
<p>- <inline-code>
<highlight>ifstream</highlight>
</inline-code> : entrée (lecture)</p>
<p>- <inline-code>
<highlight>ofstream</highlight>
</inline-code> : sortie (écriture)</p>
<p>- <inline-code>
<highlight>fstream</highlight>
</inline-code> : entrée/sortie (lecture/écriture)</p>
<p>L'ouverture peut se faire par l'appel du constructeur ou de la méthode <inline-code>
<highlight>open()</highlight>
</inline-code> ayant la même signature, seules les valeurs par défaut changent :</p>
<p><inline-code>
<highlight>ifstream::ifstream(const char* f, openmode mode = ios::in)</highlight>
</inline-code></p>
<p><inline-code>
<highlight>ofstream::ofstream(const char* f, openmode mode = ios::out)</highlight>
</inline-code></p>
<p><inline-code>
<highlight>fstream::fstream(const char* f, openmode mode = ios::in | ios::out)</highlight>
</inline-code></p>
<p>Fermeture avec la méthode <inline-code>
<highlight>close()</highlight>
</inline-code> ou automatiquement par le destructeur</p>
</section>
<section>
<h2>9.2 Les paramètres d'ouverture</h2>
<p>Le paramètre <inline-code>f</inline-code> est le nom du fichier à ouvrir</p>
<p>Le paramètre <inline-code>mode</inline-code> est un bitfield qui définit le mode d'ouverture du fichier</p>
<p>On le combine avec l'opérateur bit à bit <inline-code>|</inline-code></p>
<p><b>Exemple :</b> ouverture d'un fichier texte en écriture par ajout (à la fin)</p>
<p><inline-code>
<highlight>fstream fs("log.txt", ios::out | ios::app)</highlight>
</inline-code></p>
<p><b>Modes</b></p>
<p>- <inline-code>
<highlight>ios::binary</highlight>
</inline-code> : mode binaire (mode texte par défaut)</p>
<p>- <inline-code>
<highlight>ios::in</highlight>
</inline-code> : lecture (défaut pour <inline-code>
<highlight>ifstream</highlight>
</inline-code>)</p>
<p>- <inline-code>
<highlight>ios::out</highlight>
</inline-code> : écriture (défaut pour <inline-code>
<highlight>ofstream</highlight>
</inline-code>)</p>
<p>- <inline-code>
<highlight>ios::app</highlight>
</inline-code> : ajout à la fin (append)</p>
<p>- <inline-code>
<highlight>ios::trunc</highlight>
</inline-code> : écrase le contenu précédent (truncate)</p>
<p>- <inline-code>
<highlight>ios::ate</highlight>
</inline-code> : position à la fin dès l'ouverture</p>
</section>
<section>
<h2>9.2 Les paramètres d'ouverture</h2>
<p><b>2 manières d'ouvrir un fichier</b></p>
<br>
<p>1. Par le constructeur de la classe</p>
<p><inline-code>
<highlight>ifstream myFile("data.bin", ios::in | ios::binary)</highlight>
</inline-code></p>
<p>2. Par la méthode <inline-code>
<highlight>open()</highlight>
</inline-code></p>
<p><inline-code>
<highlight>ifstream myFile</highlight>
</inline-code></p>
<p><inline-code>
<highlight>myFile.open("data.bin", ios::in | ios::binary)</highlight>
</inline-code></p>
<p>Pour des fichiers en écriture et lecture, utiliser fstream</p>
<p><inline-code>
<highlight>fstream myFile("data.bin", ios::in | ios::out | ios::binary)</highlight>
</inline-code></p>
<br>
<p>
<warning>⚠️ Attention :</warning> mode "binaire", vraiment ? voir <a
href="https://stackoverflow.com/questions/14767857/unexpected-results-with-stdofstream-binary-write">(<<
vs .write())</a>
</p>
</section>
<section>
<h2>9.2 Exemple</h2>
<pre style="width: 1800px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 2em;"
data-line-numbers="">
#include <iostream>
#include <fstream>
int main()
{
std::ofstream fOutput("myFile.txt");
fOutput << "PI = " << 3.14159 << '.' << std::endl;
fOutput.close();
std::ifstream fInput("myFile.txt");
std::string s; double d; char c;
fInput >> s >> d >> c;
fInput.close();
std::cout << s << d << c << std::endl;
return 0;
}
</code></pre>
</section>
<section>
<h2>9.2 Exemple</h2>
<p>
<warning>⚠️ Attention</warning>
</p>
<p>L'utilisation des flux pour accéder aux fichiers soulève les mêmes problématiques que pour la console</p>
<p>En particulier, les caractères blancs sont considérés comme des séparateurs</p>
<p>On peut utiliser la fonction <inline-code>
<highlight>getline()</highlight>
</inline-code> pour lire une ligne entière</p>
</section>
<section>
<h2>9.2 Traitements d'erreurs</h2>
<p>Traitement d'erreurs identique pour tous les flux (fichier, écran/clavier, mémoire)</p>
<p>Basé sur 4 bits (flags <inline-code>ios_base::iostate</inline-code>) : <inline-code>goodbit</inline-code>,
<inline-code>badbit</inline-code>, <inline-code>failbit</inline-code> et <inline-code>eofbit</inline-code>
</p>
<p>On peut tester et manipuler l'état du flux avec les méthodes suivantes :</p>
<p>- <inline-code>
<highlight>good()</highlight>
</inline-code> : aucune erreur</p>
<p>- <inline-code>
<highlight>bad()</highlight>
</inline-code> : impossible d'extraire des données du flux</p>
<p>- <inline-code>
<highlight>fail()</highlight>
</inline-code> : échec de l'opération</p>
<p>- <inline-code>
<highlight>eof()</highlight>
</inline-code> : fin de fichier</p>
<p>- <inline-code>
<highlight>clear()</highlight>
</inline-code> : réinitialisation des bits d'état</p>
</section>
<section>
<h2>9.2 Traitements d'erreurs</h2>
<p><a href="https://en.cppreference.com/w/cpp/io/ios_base/iostate">📚 iostate (cppreference.com)</a></p>
<iframe src="https://en.cppreference.com/w/cpp/io/ios_base/iostate" width="1900" height="800"></iframe>
</section>
<section>
<h2>9.2 Traitements d'erreurs (exceptions)</h2>
<pre style="width: 1800px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
#include <iostream> // std::cerr
#include <fstream> // std::ifstream
int main () {
std::ifstream file;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
file.open("test.txt");
while(!file.eof()) file.get();
file.close();
}
catch (const std::ifstream::failure &e) {
std::cerr << "Exception opening/reading/closing file" << std::endl;
}
return 0;
}
</code></pre>
</section>
<section>
<h2>9.2 E/S Formatées ou non-formatées</h2>
<p><inline-code>
<highlight>ios::binary</highlight>
</inline-code> ⇒ s'assure que les données sont lues ou écrites sans traduire à la volée des caractères
spéciaux (ex. les caractères de fin de ligne \r\n)</p>
<!-- NOTE: we use html code here because auto-formating with << breaks the code -->
<p><inline-code>
<highlight><<</highlight>
</inline-code> ⇒ Écriture formatée (pour les fichiers textuels)</p>
<p><inline-code>
<highlight>>></highlight>
</inline-code> ⇒ Lecture formatée (pour les fichiers textuels)</p>
<p>Méthode <inline-code>
<highlight>write()</highlight>
</inline-code> ⇒ Écriture non formatée (pour les fichiers binaires)</p>
</section>
<section>
<h2>9.2 Méthodes de lecture de <span style="text-transform: lowercase;"><inline-code>
<highlight>std::istream</highlight>
</inline-code></span></h2>
<h3>Lecture formatée</h3>
<p><inline-code>
<highlight>istream &operator>>(...)</highlight>
</inline-code></p>
<p><inline-code>
<highlight>cin >> delta >> integer;</highlight>
</inline-code></p>
<h3>Lecture non formatée</h3>
<p><inline-code>
<highlight>.get</highlight>
</inline-code> : lecture d'un seul caractère</p>
<p><inline-code>
<highlight>.getline</highlight>
</inline-code> : lecture d'une suite de caractères</p>
<p><inline-code>
<highlight>.ignore</highlight>
</inline-code> : lecture de caractères «à fond perdu»</p>
<p><inline-code>
<highlight>.peek</highlight>
</inline-code> : donne le prochain caractère sans l'extraire</p>
<p><inline-code>
<highlight>.seekg</highlight>
</inline-code> : positionnement sur un flux</p>
<p><inline-code>
<highlight>.read</highlight>
</inline-code> : lecture de n caractères</p>
</section>
<section>
<h2>9.2 Méthodes de lecture de <span style="text-transform: lowercase;"><inline-code>
<highlight>std::ostream</highlight>
</inline-code></span></h2>
<h3>Écriture formatée</h3>
<!-- NOTE: we use html code here because auto-formating with << breaks the code -->
<p><inline-code>
<highlight>ostream &operator<<(...)</highlight>
</inline-code></p>
<p><inline-code>
<highlight>cout << delta << integer;</highlight>
</inline-code></p>
<h3>Écriture non formatée</h3>
<p><inline-code>
<highlight>.put</highlight>
</inline-code> : écriture d'un seul caractère</p>
<p><inline-code>
<highlight>.write</highlight>
</inline-code> : écriture du contenu du tampon</p>
<p><inline-code>
<highlight>.flush</highlight>
</inline-code> : vide le tampon de sortie</p>
<p><inline-code>
<highlight>.tellp</highlight>
</inline-code> : positionnement courant sur le flux</p>
<p><inline-code>
<highlight>.seekp</highlight>
</inline-code> : positionnement sur un flux</p>
</section>
</section>
<!---------- 9.3 Flux et std::string ---------->
<section>
<section>
<h2>9.3 Le flux <span style="text-transform: lowercase;"><inline-code>
<highlight>std::stringstream</highlight>
</inline-code></span></h2>
<p>Les flux peuvent être utilisés pour lire et écrire des chaînes de caractères</p>
<p><inline-code>
<highlight>#include <sstream></highlight>
</inline-code> ⇒ 3 classes :</p>
<p>- <inline-code>
<highlight>istringstream</highlight>
</inline-code> : entrée (lecture)</p>
<p>- <inline-code>
<highlight>ostringstream</highlight>
</inline-code> : sortie (écriture)</p>
<p>- <inline-code>
<highlight>stringstream</highlight>
</inline-code> : entrée/sortie (lecture/écriture)</p>
</section>
<section>
<h2>9.3 La classe <span style="text-transform: lowercase;"><inline-code>
<highlight>std::string</highlight>
</inline-code></span></h2>
<p>La bibliothèque standard implémente une classe <inline-code>
<highlight>std::string</highlight>
</inline-code></p>
<p><inline-code>
<highlight>#include <string></highlight>
</inline-code></p>
<p>Spécialisation d'un modèle : <inline-code>
<hightlight>typedef basic_string<char> string;</hightlight>
</inline-code></p>
<br>
<h3>Avantages</h3>
<p>- Plus simple et plus sûre que les tableaux de caractères</p>
<p>- Gestion automatique de la mémoire</p>
<p>- Définition de méthodes et d'opérateurs</p>
</section>
<section>
<h2>9.3 La classe <span style="text-transform: lowercase;"><inline-code>
<highlight>std::string</highlight>
</inline-code></span></h2>
<p><b>Opérateurs</b></p>
<p>
Affectation : <inline-code>
<highlight>=</highlight>
</inline-code>, Concaténation : <inline-code>
<highlight>+</highlight>
</inline-code> et <inline-code>
<highlight>+=</highlight>
</inline-code>, Comparaisons : <inline-code>
<highlight>==</highlight>
</inline-code> <inline-code>
<highlight><</highlight>
</inline-code> <inline-code>
<highlight>></highlight>
</inline-code> <inline-code>
<highlight><=</highlight>
</inline-code> <inline-code>
<highlight>>=</highlight>
</inline-code></p>
<p><b>Méthodes</b></p>
<p>- <inline-code>
<highlight>size()</highlight>
</inline-code> : renvoie le nombre de caractères</p>
<p>- <inline-code>
<highlight>length()</highlight>
</inline-code> : renvoie le nombre de caractères</p>
<p>- <inline-code>
<highlight>capacity()</highlight>
</inline-code> : taille possible sans réallocation</p>
<p>- <inline-code>
<highlight>empty()</highlight>
</inline-code> : vrai si la chaîne est vide, faux sinon</p>
<p>- <inline-code>
<highlight>find()</highlight>
</inline-code> : position de la chaîne <inline-code>s</inline-code> dans la chaîne courante à partir
de<inline-code>pos</inline-code></p>
<p>- <inline-code>
<highlight>substr()</highlight>
</inline-code> : sous-chaîne de longueur <inline-code>length</inline-code> à partir
de<inline-code>start</inline-code></p>
<p>- <inline-code>
<highlight>at()</highlight>
</inline-code> : accès à un caractère par son index</p>
<p>- <inline-code>
<highlight>c_str()</highlight>
</inline-code> : renvoie un pointeur vers le tableau de caractères</p>
</section>
<section>
<h2>9.3 Conversions entre <span style="text-transform: lowercase;"><inline-code>
<highlight>std::string</highlight>
</inline-code></span> et <span style="text-transform: lowercase;"><inline-code>
<highlight>char *</highlight>
</inline-code></span></h2>
<pre style="width: 1400px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <iostream>
#include <string>
#include <cstdio>
int main()
{
auto p = "Hello"; // const char *
auto s = std::string(p);
auto s2 = std::string("World!");
std::cout << s << " " << s2 << std::endl;
printf("%s %s\n", s, s2); // ⚠️ warning C4477: 'printf'...
auto p2 = s2.c_str(); // const char *
std::cout << p << " " << p2 << std::endl;
printf("%s %s\n", p, p2);
return 0;
}
</code></pre>
</section>
<section>
<h2>9.3 Conversions avec les flux de chaîne</h2>
<pre style="width: 1000px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::ostringstream toto;
toto << 10;
auto texte = toto.str();
std::istringstream titi("10");
int nombre;
titi >> nombre;
return 0;
}
</code></pre>
</section>
<section>
<h2>Les flux (vue d'ensemble)</h2>
<p><a href="https://en.cppreference.com/w/cpp/io#Stream-based_I.2FO">📚 Stream-based I/O
(cppreference.com)</a></p>
<iframe src="https://en.cppreference.com/w/cpp/io#Stream-based_I.2FO" width="1900" height="800"></iframe>
</section>
</section>
<!---------- 9.4 Conteneurs séquentiels ---------->
<section>
<section>
<h2>9.4 Standard Template Library (STL)</h2>
<p>Bibliothèque de classes et d'algorithmes génériques (A. Stepanov)</p>
<p>Implémentée en C++</p>
<p>Intégrée à la procédure de standardisation de C++</p>
<p>Basée sur les modèles de classes</p>
<p><b>Contient</b></p>
<p>- Conteneurs séquentiels</p>
<p>- Conteneurs associatifs</p>
<p>- Itérateurs</p>
<p>- Algorithmes</p>
<p>- Objets fonctions (foncteurs)</p>
<p>- Adaptateurs</p>
<p>- Allocateurs</p>
</section>
<section>
<h2>9.4 Les conteneurs</h2>
<p>Les conteneurs sont des classes qui permettent de stocker des objets</p>
<p>Ils sont définis dans le namespace <inline-code>
<highlight>std</highlight>
</inline-code></p>
<p>Gérer les objets contenus : ajout, suppression (parfois tri, recherche, ...)</p>
<p>Accéder aux objets contenus grâce aux itérateurs</p>
<p>Les itérateurs permettent de parcourir une collection d'objets sans avoir à se préoccuper de
l'implémentation</p>
<p>⇒ Avoir une interface de manipulation commune pour les algorithmes génériques de la STL (tri, recherche,
remplacement, ...)</p>
</section>
<section>
<h2>9.4 Les conteneurs</h2>
<h3>2 types de conteneurs</h3>
<br>
<p><b>Conteneurs séquentiels</b></p>
<p>Conteneurs dont les éléments sont ordonnés. Parcourir le conteneur suivant cet ordre et insérer ou
supprimer un élément en un endroit explicitement choisi.</p>
<p><inline-code>
<highlight>vector</highlight>
</inline-code>,
<inline-code>
<highlight>list</highlight>
</inline-code>,
<inline-code>
<highlight>deque</highlight>
</inline-code>, ...
</p>
<br>
<p><b>Conteneurs associatifs</b></p>
<p>Conteneurs dont les éléments sont identifiés par une clé et ordonnés suivant celle-ci. Pour insérer un
élément, il n'est en théorie pas utile de préciser un emplacement.</p>
<p><inline-code>
<highlight>map</highlight>
</inline-code>, ...</p>
</section>
<section>
<h2>9.4 Les conteneurs séquentiels</h2>
<p>Tableau dynamique contigu : <inline-code>
<highlight>vector</highlight>
</inline-code></p>
<p>Tableau statique contigu : <inline-code>
<highlight>array</highlight>
</inline-code></p>
<p>File à double entrée : <inline-code>
<highlight>deque</highlight>
</inline-code></p>
<p>Liste doublement chainée : <inline-code>
<highlight>list</highlight>
</inline-code></p>
<p>Liste simplement chainée : <inline-code>
<highlight>forward_list</highlight>
</inline-code></p>
<p>File : <inline-code>
<highlight>queue</highlight>
</inline-code>, <inline-code>
<highlight>priority_queue</highlight>
</inline-code></p>
<p>Pile : <inline-code>
<highlight>stack</highlight>
</inline-code></p>
</section>
<section>
<h2>9.4 Méthodes courantes</h2>
<p><inline-code>
<highlight>clear()</highlight>
</inline-code> : vide le conteneur</p>
<p><inline-code>
<highlight>size()</highlight>
</inline-code> : retourne le nombre d'éléments</p>
<p><inline-code>
<highlight>empty()</highlight>
</inline-code> : teste si le conteneur est vide</p>
<p><inline-code>
<highlight>push_back(...)</highlight>
</inline-code> : ajoute un élément à la fin</p>
<p><inline-code>
<highlight>push_front(...)</highlight>
</inline-code> : ajoute un élément au début</p>
<p><inline-code>
<highlight>front()</highlight>
</inline-code> : renvoie le 1er élément</p>
<p><inline-code>
<highlight>pop_front()</highlight>
</inline-code> : supprime le premier élément</p>
<p><inline-code>
<highlight>insert()</highlight>
</inline-code> : insère un élément</p>
<p><inline-code>
<highlight>erase()</highlight>
</inline-code> : supprime un élément</p>
</section>
<section>
<h2>9.4 Exemple</h2>
<pre style="width: 1400px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> vect;
vect.push_back("Introduction");
vect.push_back("une phrase");
vect.push_back("Conclusion");
for (const auto &elem : vect)
std::cout << elem << std::endl;
for (int i = 0; i < vect.size(); ++i)
std::cout << vect[i] << std::endl;
return 0;
}
</code></pre>
</section>
<section>
<h2>9.4 Exemple</h2>
<pre style="width: 1400px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <list>
int main()
{
std::list<int> lst;
lst.push_back(1); // 1
lst.push_front(0); // 0 1
lst.insert(lst.begin(), 2); // 2 0 1
lst.insert(lst.end(), 3); // 2 0 1 3
lst.pop_front(); // 0 1 3
return 0;
}
</code></pre>
</section>
<section>
<h2>9.4 Exemple</h2>
<pre style="width: 1800px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <print>
#include <array>
int main()
{
std::array<int, 3> a1{ {10,11,12} };
// std::array<int, 3> a1 = { 10,11,12 };
for (int i = 0; i < a1.size(); ++i)
{
std::println("{}", a1[i]); // ⚠️ no range check
std::println("{}", a1.at(i)); // ✅ range check (throws exception)
}
return 0;
}
</code></pre>
</section>
<section>
<h2>9.4 Destruction</h2>
<h3>Faut-il effacer ce qui est stocké dans un vecteur ?</h3>
<p>⇒ Tout dépend de la nature de ce qui est stocké dans le <inline-code>
<highlight>std::vector</highlight>
</inline-code></p>
<br>
<p><b>Objets</b></p>
<p>Les objets sont détruits lors du retrait (pop), ou lorsque le vecteur est détruit</p>
<br>
<p><b>Pointeurs</b></p>
<p>Les pointeurs sont détruits lorsque le vecteur est détruit <b>
<warning>mais pas la mémoire allouée !</warning>
</b></p>
<p>⇒ Il faut <inline-code>
<highlight>delete</highlight>
</inline-code> chaque pointeur stocké, sinon il y aura une fuite de mémoire.</p>
</section>
<section>
<h2>9.4 Imbrication de conteneurs</h2>
<p>Il est possible d'imbriquer les conteneurs de la STL</p>
<p>On peut ainsi, par exemple, créer un vecteur de listes de chaînes de caractères</p>
<br>
<p><b>Exemple</b></p>
<p><inline-code>
<highlight>std::vector<std::list<std::string>></highlight>
</inline-code></p>
<br>
<p>La définition d'un type intermédiaire peut augmenter la lisibilité :</p>
<p><inline-code>
<highlight>using list_string = std::list<std::string>;</highlight>
</inline-code></p>
<p><inline-code>
<highlight>using vector_list_string = std::vector<list_string>;</highlight>
</inline-code></p>
</section>
<section>
<h2>9.4 Imbrication de conteneurs</h2>
<p>Des <inline-code>std::vector</inline-code> imbriqués simulent des tableaux à plusieurs dimensions</p>
<pre style="width: 1400px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
#include <vector>
using Line = std::vector<double>;
using Matrix = std::vector<Line>;
Matrix m(5); // 5 rows of size 0 initially
for(auto i = 0; i < 5; ++i)
{
m[i].resize(5); // rows are now of size 5
for(auto j = 0; j < 5; ++j)
{
if (i == j) m[i][j] = 1;
else m[i][j] = 0;
}
}
</code></pre>
</section>
</section>
<!---------- 9.5 Itérateurs ---------->
<section>
<section>
<h2>9.5 Les itérateurs</h2>
<p>Les itérateurs sont une <b>généralisation des pointeurs</b></p>
<p>Définis dans le namespace <inline-code>
<highlight>std</highlight>
</inline-code></p>
<p>Utilisés par les algorithmes de la STL</p>
<p>Utiliser les conteneurs <b>de façon uniforme</b></p>
<p>Spécifier une position à l'intérieur d'un conteneur. Ils peuvent être incrémentés, et déréférencés (avec
*); deux itérateurs peuvent être comparés.</p>
<p><b>Tous les conteneurs disposent des méthodes suivantes</b></p>
<p><inline-code>
<highlight>begin()</highlight>
</inline-code> : renvoie un itérateur pointant sur le 1er élément</p>
<p><inline-code>
<highlight>end()</highlight>
</inline-code> : renvoie un itérateur pointant <b>APRES</b> le dernier élément</p>
<p>
<warning>⚠️ On ne peut donc pas déréférencer l'itérateur renvoyé par <inline-code>
<highlight>end()</highlight>
</inline-code></warning>
</p>
</section>
<section>
<h2>9.5 Les itérateurs</h2>
<h3>Déclarations</h3>
<p><inline-code>
<highlight>std::vector<double>::iterator it;</highlight>
</inline-code></p>
<br>
<p>Un itérateur peut s'initialiser grâce aux méthodes <inline-code>
<highlight>begin()</highlight>
</inline-code>, <inline-code>
<highlight>end()</highlight>
</inline-code>, ou <inline-code>
<highlight>find()</highlight>
</inline-code> :</p>
<p>1) <inline-code>
<highlight>std::vector<double>::iterator it(vect.begin());</highlight>
</inline-code></p>
<p>2) <inline-code>
<highlight>auto it = vect.begin();</highlight>
</inline-code></p>
</section>
<section>
<h2>9.5 Exemple</h2>
<pre style="width: 1600px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.6em;"
data-line-numbers="">
#include <iostream>
#include <list>
int main()
{
std::list<int> lst;
std::list<int>::iterator it;
for (it = lst.begin(); it != lst.end(); ++it)
std::println("{}", *it); // *it = each element
// C++11
for (auto it = lst.begin(); it != lst.end(); ++it)
std::println("{}", *it); // *it = each element
// C++11 range-based for loop
for (auto &elem : lst)
std::println("{}", elem); // elem = each element
}
</code></pre>
</section>
</section>
<!---------- 9.6 Conteneurs associatifs ---------->
<section>
<section>
<h2>9.6 Conteneurs associatifs</h2>
<p>Les conteneurs associatifs sont des conteneurs qui stockent des éléments sous forme de paires clé/valeur
</p>
<p>Les clés permettent d'accéder aux valeurs</p>
<p>Les conteneurs associatifs sont ordonnés selon la clé</p>
<br>
<p><inline-code>
<highlight>std::map</highlight>
</inline-code>, <inline-code>
<highlight>std::multimap</highlight>
</inline-code>, <inline-code>
<highlight>std::set</highlight>
</inline-code>, <inline-code>
<highlight>std::multiset</highlight>
</inline-code>, ...</p>
<br>
<p>Ces conteneurs utilisent <inline-code>
<highlight>std::pair<T1, T2></highlight>
</inline-code> pour stocker les paires clé/valeur</p>
</section>
<section>
<h2>9.6 Tables associatives</h2>
<p>Généralisation des tableaux : les indices peuvent être non entiers</p>
<p>- Tableau que l'on pourrait indicer par des chaînes de caractères et écrire par exemple <inline-code>
<highlight>moyenne["Informatique"]</highlight>
</inline-code></p>
<p>- On parle d'association "clé - valeur"</p>
<p>Les tables associatives sont définies dans <inline-code>
<highlight><map></highlight>
</inline-code></p>
<p>Elles nécessitent 2 types pour leur déclaration : le type des "clés" (les index) et le type des éléments
indexés</p>
<pre style="width: 1600px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <string>
#include <map>
std::map<std::string, double> moyenneParBranche; // Unique key
std::multimap<std::string, double> notesParBranche; // Duplicated keys
</code></pre>
</section>
<section>
<h2>9.6 Exemple</h2>
<pre style="width: 1600px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
#include <string>
#include <map>
#include <iostream>
int main()
{
std::map<std::string, double> moyenne;
moyenne["Informatique"] = 5.5;
moyenne["Physique"] = 4.5;
// it->first to access the key, it->second to access the value
for (auto it = moyenne.begin(); it != moyenne.end(); ++it)
std::cout << "En " << it->first << ", j'ai " << it->second <<
" de moyenne." << std::endl ;
std::cout << "Ma moyenne en Informatique est de ";
std::cout << moyenne.find("Informatique")->second << std::endl;
return 0;
}
</code></pre>
</section>
<section>
<h2>9.6 Exemple</h2>
<pre style="width: 1600px;"><code
class="c++"
data-trim