-
Notifications
You must be signed in to change notification settings - Fork 0
/
c-programming.html
1152 lines (992 loc) · 168 KB
/
c-programming.html
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 SYSTEM "about:legacy-compat">
<html lang="en-US" data-preset="contrast" data-primary-color="#6860F6" data-link-color="#307FFF" data-resizable-sidebar="true" data-sidebar-width="260"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta charset="UTF-8"><meta name="built-on" content="2024-11-14T14:28:58.8778664"><title>C++ Programming | Computer Science Study Notes</title><script type="application/json" id="virtual-toc-data">[{"id":"c-fundamentals","level":0,"title":"Ⅰ C++ Fundamentals","anchor":"#c-fundamentals"},{"id":"intro","level":1,"title":"1 C \u0026 C++ Introduction","anchor":"#intro"},{"id":"2-types-and-structs","level":1,"title":"2 Types and Structs","anchor":"#2-types-and-structs"},{"id":"2-1-primitive-types","level":2,"title":"2.1 Primitive Types","anchor":"#2-1-primitive-types"},{"id":"structs","level":2,"title":"2.2 Structs","anchor":"#structs"},{"id":"3-initialization-references","level":1,"title":"3 Initialization \u0026 References","anchor":"#3-initialization-references"},{"id":"3-1-initialization","level":2,"title":"3.1 Initialization","anchor":"#3-1-initialization"},{"id":"3-2-references","level":2,"title":"3.2 References","anchor":"#3-2-references"},{"id":"4-streams","level":1,"title":"4 Streams","anchor":"#4-streams"},{"id":"4-1-strings","level":2,"title":"4.1 Strings","anchor":"#4-1-strings"},{"id":"4-2-stringstreams","level":2,"title":"4.2 Stringstreams","anchor":"#4-2-stringstreams"},{"id":"4-3-input-streams","level":2,"title":"4.3 Input Streams","anchor":"#4-3-input-streams"},{"id":"4-4-output-streams","level":2,"title":"4.4 Output Streams","anchor":"#4-4-output-streams"},{"id":"5-modern-c-types","level":1,"title":"5 Modern C++ Types","anchor":"#5-modern-c-types"},{"id":"5-1-auto","level":2,"title":"5.1 Auto","anchor":"#5-1-auto"},{"id":"5-2-pair-tuple","level":2,"title":"5.2 Pair/Tuple","anchor":"#5-2-pair-tuple"},{"id":"5-3-conversions","level":2,"title":"5.3 Conversions","anchor":"#5-3-conversions"},{"id":"5-4-initializer-list","level":2,"title":"5.4 initializer_list","anchor":"#5-4-initializer-list"},{"id":"5-5-using","level":2,"title":"5.5 using","anchor":"#5-5-using"},{"id":"standard-template-library-stl","level":0,"title":"Ⅱ Standard Template Library (STL)","anchor":"#standard-template-library-stl"},{"id":"6-containers","level":1,"title":"6 Containers","anchor":"#6-containers"},{"id":"6-1-sequence-containers","level":2,"title":"6.1 Sequence Containers","anchor":"#6-1-sequence-containers"},{"id":"6-2-container-adapters","level":2,"title":"6.2 Container Adapters","anchor":"#6-2-container-adapters"},{"id":"6-3-associative-containers","level":2,"title":"6.3 Associative Containers","anchor":"#6-3-associative-containers"},{"id":"iterators","level":2,"title":"6.4 Iterators","anchor":"#iterators"},{"id":"7-templates","level":1,"title":"7 Templates","anchor":"#7-templates"},{"id":"7-1-template-functions","level":2,"title":"7.1 Template Functions","anchor":"#7-1-template-functions"},{"id":"7-2-template-classes","level":2,"title":"7.2 Template Classes","anchor":"#7-2-template-classes"},{"id":"8-functions-and-algorithms","level":1,"title":"8 Functions and Algorithms","anchor":"#8-functions-and-algorithms"},{"id":"Lambda","level":2,"title":"8.1 Lambda Functions","anchor":"#Lambda"},{"id":"8-2-algorithms","level":2,"title":"8.2 Algorithms","anchor":"#8-2-algorithms"},{"id":"object","level":0,"title":"Ⅲ Object-Oriented Programming","anchor":"#object"},{"id":"9-classes-and-consts","level":1,"title":"9 Classes and Consts","anchor":"#9-classes-and-consts"},{"id":"9-1-classes","level":2,"title":"9.1 Classes","anchor":"#9-1-classes"},{"id":"9-2-consts","level":2,"title":"9.2 Consts","anchor":"#9-2-consts"},{"id":"10-operators","level":1,"title":"10 Operators","anchor":"#10-operators"},{"id":"10-1-basic-operators","level":2,"title":"10.1 Basic Operators","anchor":"#10-1-basic-operators"},{"id":"10-2-operator-overloading","level":2,"title":"10.2 Operator Overloading","anchor":"#10-2-operator-overloading"},{"id":"10-3-principle-of-least-astonishment-pola","level":2,"title":"10.3 Principle of Least Astonishment (POLA)","anchor":"#10-3-principle-of-least-astonishment-pola"},{"id":"10-4-interesting-operators","level":2,"title":"10.4 Interesting Operators","anchor":"#10-4-interesting-operators"},{"id":"11-special-member-functions","level":1,"title":"11 Special Member Functions","anchor":"#11-special-member-functions"},{"id":"11-1-copy-constructor-copy-assignment-operator","level":2,"title":"11.1 Copy Constructor \u0026 Copy Assignment Operator","anchor":"#11-1-copy-constructor-copy-assignment-operator"},{"id":"11-2-delete-operations","level":2,"title":"11.2 Delete Operations","anchor":"#11-2-delete-operations"},{"id":"11-3-rule-of-zero-three","level":2,"title":"11.3 Rule of Zero/Three","anchor":"#11-3-rule-of-zero-three"},{"id":"11-4-copy-elision-and-return-value-optimization-rvo","level":2,"title":"11.4 Copy Elision and Return Value Optimization (RVO)","anchor":"#11-4-copy-elision-and-return-value-optimization-rvo"},{"id":"12-move-semantics","level":1,"title":"12 Move Semantics","anchor":"#12-move-semantics"},{"id":"12-1-lvalues-rvalues","level":2,"title":"12.1 lvalues \u0026 rvalues","anchor":"#12-1-lvalues-rvalues"},{"id":"12-2-move-semantics","level":2,"title":"12.2 Move Semantics","anchor":"#12-2-move-semantics"},{"id":"inheritance","level":1,"title":"13 Inheritance","anchor":"#inheritance"},{"id":"13-1-namespace","level":2,"title":"13.1 Namespace","anchor":"#13-1-namespace"},{"id":"13-1-overriding-and-overloading","level":2,"title":"13.1 Overriding and Overloading","anchor":"#13-1-overriding-and-overloading"},{"id":"13-2-types-of-inheritance","level":2,"title":"13.2 Types of Inheritance","anchor":"#13-2-types-of-inheritance"},{"id":"modern-c","level":0,"title":"Ⅳ Modern C++","anchor":"#modern-c"},{"id":"14-raii","level":1,"title":"14 RAII","anchor":"#14-raii"}]</script><script type="application/json" id="topic-shortcuts"></script><link href="https://resources.jetbrains.com/writerside/apidoc/6.10.0-b518/app.css" rel="stylesheet"><link href="static/custom.css" rel="stylesheet"><link rel="icon" type="image/png" sizes="16x16" href="Computer-Science-Study-Notes/photo.png"><meta name="image" content=""><!-- Open Graph --><meta property="og:title" content="C++ Programming | Computer Science Study Notes"><meta property="og:description" content=""><meta property="og:image" content=""><meta property="og:site_name" content="Computer Science Study Notes Help"><meta property="og:type" content="website"><meta property="og:locale" content="en_US"><meta property="og:url" content="writerside-documentation/c-programming.html"><!-- End Open Graph --><!-- Twitter Card --><meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content=""><meta name="twitter:title" content="C++ Programming | Computer Science Study Notes"><meta name="twitter:description" content=""><meta name="twitter:creator" content=""><meta name="twitter:image:src" content=""><!-- End Twitter Card --><!-- Schema.org WebPage --><script type="application/ld+json">{
"@context": "http://schema.org",
"@type": "WebPage",
"@id": "writerside-documentation/c-programming.html#webpage",
"url": "writerside-documentation/c-programming.html",
"name": "C++ Programming | Computer Science Study Notes",
"description": "",
"image": "",
"inLanguage":"en-US"
}</script><!-- End Schema.org --><!-- Schema.org WebSite --><script type="application/ld+json">{
"@type": "WebSite",
"@id": "writerside-documentation/#website",
"url": "writerside-documentation/",
"name": "Computer Science Study Notes Help"
}</script><!-- End Schema.org --></head><body data-id="C-Programming" data-main-title="C++ Programming" data-article-props="{"seeAlsoStyle":"links"}" data-template="article" data-breadcrumbs=""><div class="wrapper"><main class="panel _main"><header class="panel__header"><div class="container"><h3>Computer Science Study Notes Help</h3><div class="panel-trigger"></div></div></header><section class="panel__content"><div class="container"><article class="article" data-shortcut-switcher="inactive"><h1 data-toc="C-Programming" id="C-Programming.topic">C++ Programming</h1><section class="chapter"><h2 id="c-fundamentals" data-toc="c-fundamentals">Ⅰ C++ Fundamentals</h2><section class="chapter"><h3 id="intro" data-toc="intro">1 C & C++ Introduction</h3><p id="z7hbb6_14"><span id="z7hbb6_22"><font style="color:#8a2be2">Properties:</font></span></p><ul class="list _bullet" id="z7hbb6_15"><li class="list__item" id="z7hbb6_23"><p id="z7hbb6_25">C/C++ is a <span id="z7hbb6_26"><font style="color:#ff4500">compiled</font></span> language.</p></li><li class="list__item" id="z7hbb6_24"><p id="z7hbb6_27">C/C++ <span id="z7hbb6_29"><i>compilers</i></span> map C/C++ programs into architecture-specific machine code (string of 0s and 1s).</p><ul class="list _bullet" id="z7hbb6_28"><li class="list__item" id="z7hbb6_30"><p id="z7hbb6_33">Unlike Java, which converts to architecture-independent bytecode (run by JVM => Java Virtual Machine).</p></li><li class="list__item" id="z7hbb6_31"><p id="z7hbb6_34">Unlike Python, which directly <span id="z7hbb6_35"><i>interprets</i></span> the code.</p></li><li class="list__item" id="z7hbb6_32"><p id="z7hbb6_36">Main difference is when your program is mapped to low-level machine instructions, CPU will directly interprets and runs.</p></li></ul></li></ul><p id="z7hbb6_16"><span id="z7hbb6_37"><font style="color:#8a2be2">Compilation Advantages:</font></span></p><ul class="list _bullet" id="z7hbb6_17"><li class="list__item" id="z7hbb6_38"><p id="z7hbb6_40"><span id="z7hbb6_42"><font style="color:#ff00ff">Excellent run-time performance:</font></span></p><p id="z7hbb6_41">Generally much faster than Python or Java for comparable code because it <span id="z7hbb6_43"><font style="color:#ff4500">optimizes for the given architecture</font></span>.</p></li><li class="list__item" id="z7hbb6_39"><p id="z7hbb6_44"><span id="z7hbb6_46"><font style="color:#ff00ff">Fair compilation time:</font></span></p><p id="z7hbb6_45">Enhancements in compilation procedure (Makefiles) allow us to <span id="z7hbb6_47"><font style="color:#ff4500">recompile only the modified files</font></span>.</p></li></ul><p id="z7hbb6_18"><span id="z7hbb6_48"><font style="color:#8a2be2">Compilation Disadvantages:</font></span></p><ul class="list _bullet" id="z7hbb6_19"><li class="list__item" id="z7hbb6_49"><p id="z7hbb6_51">Compiled files, including the executable, are arcitecture-specific (CPU type and OS).</p><ul class="list _bullet" id="z7hbb6_52"><li class="list__item" id="z7hbb6_53"><p id="z7hbb6_55">Executable must be <span id="z7hbb6_56"><font style="color:#ff4500">rebuilt</font></span> on each new system.</p></li><li class="list__item" id="z7hbb6_54"><p id="z7hbb6_57">i.e. "porting your code" to a new architecture.</p></li></ul></li><li class="list__item" id="z7hbb6_50"><p id="z7hbb6_58">Instead of "Edit -> Run [repeat]" cycle, "Edit -> Compile -> Run [repeat]" iteration cycle can be slow.</p></li></ul><figure id="z7hbb6_20"><img alt="Compilation" src="Computer-Science-Study-Notes/c1-1.png" title="Compilation" width="4332" height="987"></figure><aside class="prompt" data-type="note" data-title="" id="z7hbb6_21"><p id="z7hbb6_59">For more information about how to compile and run the code, please refer to Computer Architecture part.</p></aside></section><section class="chapter"><h3 id="2-types-and-structs" data-toc="2-types-and-structs">2 Types and Structs</h3><section class="chapter"><h4 id="2-1-primitive-types" data-toc="2-1-primitive-types">2.1 Primitive Types</h4><div class="table-wrapper"><table class="wide" id="z7hbb6_62"><thead><tr class="ijRowHead" id="z7hbb6_63"><th id="z7hbb6_70"><p>Fundamental Types</p></th><th id="z7hbb6_71"><p>Example</p></th><th id="z7hbb6_72"><p>Memory</p></th></tr></thead><tbody><tr id="z7hbb6_64"><td id="z7hbb6_73"><p>int</p></td><td id="z7hbb6_74"><div class="code-block" data-lang="cpp">int val = 5;</div></td><td id="z7hbb6_75"><p>32 bits (usually)</p></td></tr><tr id="z7hbb6_65"><td id="z7hbb6_77"><p>char</p></td><td id="z7hbb6_78"><div class="code-block" data-lang="cpp">char ch = 'F';</div></td><td id="z7hbb6_79"><p>8 bits (usually)</p></td></tr><tr id="z7hbb6_66"><td id="z7hbb6_81"><p>float</p></td><td id="z7hbb6_82"><div class="code-block" data-lang="cpp">float decimalVal1 = 5.0;</div></td><td id="z7hbb6_83"><p>32 bits (usually)</p></td></tr><tr id="z7hbb6_67"><td id="z7hbb6_85"><p>double</p></td><td id="z7hbb6_86"><div class="code-block" data-lang="cpp">double decimalVal2 = 5.0;</div></td><td id="z7hbb6_87"><p>64 bits (usually)</p></td></tr><tr id="z7hbb6_68"><td id="z7hbb6_89"><p>bool</p></td><td id="z7hbb6_90"><div class="code-block" data-lang="cpp">bool bVal = true;</div></td><td id="z7hbb6_91"><p>1 bit</p></td></tr><tr id="z7hbb6_69"><td id="z7hbb6_93"><p>std::string</p></td><td id="z7hbb6_94"><div class="code-block" data-lang="cpp">std::string str = "Haven";</div></td><td id="z7hbb6_95"><p>Depends on architecture</p></td></tr></tbody></table></div></section><section class="chapter"><h4 id="structs" data-toc="structs">2.2 Structs</h4><p id="z7hbb6_97"><span id="z7hbb6_101"><font style="color:#8a2be2">Definition:</font></span></p><p id="z7hbb6_98"><span id="z7hbb6_102"><font style="color:#ff8c00">Struct:</font></span> A <span id="z7hbb6_103"><b>struct</b></span> is a group of <span id="z7hbb6_104"><b>named variables</b></span>, each with their own type, that allows programmers to <span id="z7hbb6_105"><b>bundle different types</b></span> together!</p><p id="z7hbb6_99"><span id="z7hbb6_106"><font style="color:#8a2be2">Example:</font></span></p><div class="code-comparer" id="z7hbb6_100" data-comparing="horizontally"><div class="code-block" data-lang="cpp" data-title="C++">
struct Student {
string name; // these are called fields
string state; // separate these by semicolons
int age;
};
Student s;
s.name = "Haven";
s.state = "AR";
s.age = 22; // use . to access fields
</div><div class="code-block" data-lang="c" data-title="C">
typedef struct {
char name[50];
char state[3];
int age;
} Student;
Student s;
strcpy(s.name, "Haven");
strcpy(s.state, "AR");
s.age = 22; // use . to access fields
</div></div></section></section><section class="chapter"><h3 id="3-initialization-references" data-toc="3-initialization-references">3 Initialization & References</h3><section class="chapter"><h4 id="3-1-initialization" data-toc="3-1-initialization">3.1 Initialization</h4><p id="z7hbb6_111">There are three types of initialization:</p><ol class="list _alpha-lower" id="z7hbb6_112" type="a"><li class="list__item" id="z7hbb6_115"><p id="z7hbb6_118"><span id="z7hbb6_120"><font style="color:#ff00ff">Direct Initialization:</font></span></p><div class="code-block" data-lang="cpp">
int numOne = 12.0;
// numOne = 12, doesn't type check with direct initialization
</div></li><li class="list__item" id="z7hbb6_116"><p id="z7hbb6_121"><span id="z7hbb6_123"><font style="color:#ff00ff">Uniform Initialization (C++ 11):</font></span></p><div class="code-block" data-lang="cpp">
int numTwo {12.0};
// narrowing conversion of '1.2e+1' from 'double' to 'int'
// type checks with uniform initialization
</div></li><li class="list__item" id="z7hbb6_117"><p id="z7hbb6_124"><span id="z7hbb6_126"><font style="color:#ff00ff">Structured binding (C++ 17):</font></span> Can access multiple values returned by a function.</p><div class="code-block" data-lang="cpp">
#include <iostream>
#include <tuple>
#include <string>
std::tuple<std::string, std::string, std::string> getclassInfo() {
std::string className = "CS106L";
std::string buildingName = "Turing Auditorium";
std::string language = "C++";
return {className, buildingName, language};
}
int main() {
auto [className, buildingName, language] = getclassInfo();
std::cout << "Come to " << buildingName << " and join us for " <<
className << " to learn " << language << "!" << std::endl;
// Output: Come to Turing Auditorium and join us for CS106L to learn C++!
return 0;
}
</div></li></ol><p id="z7hbb6_113"><span id="z7hbb6_127"><font style="color:#8a2be2">Advantages for Uniform Initialization:</font></span></p><ol class="list _decimal" id="z7hbb6_114" type="1"><li class="list__item" id="z7hbb6_128"><p id="z7hbb6_130">It's safe! It doesn't allow for narrowing conversions — which can lead to unexpected behaviour (or critical system failures)</p></li><li class="list__item" id="z7hbb6_129"><p id="z7hbb6_131">It's ubiquitous! it works for all types like vectors, maps, and custom classes, among other things!</p></li></ol></section><section class="chapter"><h4 id="3-2-references" data-toc="3-2-references">3.2 References</h4><p id="z7hbb6_132"><span id="z7hbb6_136"><font style="color:#8a2be2">Example:</font></span></p><div class="code-block" data-lang="cpp">
int x = 5;
int& ref = x; // ref is a reference to x
ref = 10; // x is now 10
</div><p id="z7hbb6_134"><span id="z7hbb6_137"><font style="color:#8a2be2">A classic reference-copy bug:</font></span></p><div class="code-comparer" id="z7hbb6_135" data-comparing="horizontally"><div class="code-block" data-lang="cpp" data-title="Bug">
// We are modifying the std::pair's inside of nums
void shift(std::vector<std::pair<int, int&gtl> &nums) { // nums passed by reference
for (auto [num1, num2] : nums) { // num1 and num2 are copies
num1++;
num2++;
}
}
</div><div class="code-block" data-lang="cpp" data-title="Fixed">
// Correct Way
void shift(std::vector<std::pair<int, int>> &nums) {
for (auto& [num1, num2] : nums) {
num1++;
num2++;
}
}
</div></div></section></section><section class="chapter"><h3 id="4-streams" data-toc="4-streams">4 Streams</h3><section class="chapter"><h4 id="4-1-strings" data-toc="4-1-strings">4.1 Strings</h4><p id="z7hbb6_144">For more information on strings, please visit <a href="data-structures-and-algorithms-3.html#strings-in-java" id="z7hbb6_147" data-tooltip="Strings in Java">strings in Java</a>.</p><p id="z7hbb6_145"><span id="z7hbb6_148"><font style="color:#8a2be2">Examples in C++:</font></span></p><div class="code-block" data-lang="cpp">
std::string str = "Hello, World!";
std::cout << str[1] << std::endl; // e
str[1] = 'a'; // Hallo, World!
</div></section><section class="chapter"><h4 id="4-2-stringstreams" data-toc="4-2-stringstreams">4.2 Stringstreams</h4><ul class="list _bullet" id="z7hbb6_149"><li class="list__item" id="z7hbb6_154"><p id="z7hbb6_156">Constructors with initialtext in the buffer.</p></li><li class="list__item" id="z7hbb6_155"><p id="z7hbb6_157">Can optionally provide "modes" such as ate (start at end) or bin (read as binary).</p></li></ul><section class="chapter"><h5 id="4-2-1-output-stringstreams" data-toc="4-2-1-output-stringstreams">4.2.1 Output Stringstreams</h5><p id="z7hbb6_158"><span id="z7hbb6_162"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-block" data-lang="cpp">
std::ostringstream oss("Ito-En Green Tea");
std::cout << oss.str() << std::endl; // Ito-En Green Tea
oss << "16.9 Ounces";
std::cout << oss.str() << std::endl; // 16.9 Ouncesn Tea
std::ostringstream oss("Ito-En Green Tea", std::ostringstream::ate);
oss << "16.9 Ounces";
std::cout << oss.str() << std::endl; // Ito-En Green Tea16.9 Ounces
</div><p id="z7hbb6_160"><span id="z7hbb6_163"><font style="color:#8a2be2">Positioning Functions:</font></span></p><ol class="list _decimal" id="z7hbb6_161" type="1"><li class="list__item" id="z7hbb6_164"><p id="z7hbb6_166"><span id="z7hbb6_169"><font style="color:#ff00ff">tellp()</font></span></p><p id="z7hbb6_167">Returns the current position of the put pointer in the output string stream.</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <sstream>
int main() {
std::ostringstream oss;
oss << "Hello";
std::streampos currentPos = oss.tellp();
std::cout << "Current put pointer position: " << currentPos <<
std::endl; // Output: 5
oss << " World!";
currentPos = oss.tellp();
std::cout << "New put pointer position: " << currentPos << std::endl;
// Output: 12
return 0;
}
</div></li><li class="list__item" id="z7hbb6_165"><p id="z7hbb6_170"><span id="z7hbb6_174"><font style="color:#ff00ff">seekp(pos)</font></span></p><p id="z7hbb6_171">Moves the put pointer to a specific position within the output string stream.</p><p id="z7hbb6_172">The position can be an absolute offset from the beginning of the stream, or a relative offset from the current position (using std::ios::beg, std::ios::cur, or std::ios::end as a second argument).</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <sstream>
int main() {
std::ostringstream oss;
oss << "Hello World!";
// 1. Absolute positioning (from the beginning)
oss.seekp(0); // Move to the beginning
oss << "Hi"; // Overwrite "Hello"
std::cout << oss.str() << std::endl; // Output: Hi World!
// 2. Relative positioning (from the end)
oss.seekp(-2, std::ios::end); // Move 2 positions back from the end
oss << "???"; // Overwrite "d!"
std::cout << oss.str() << std::endl; // Output: Hi Worl???
// 3. Using std::ios::beg (from the beginning)
oss.seekp(5, std::ios::beg); // Move 5 positions from the beginning
oss << "-"; // Insert "-"
std::cout << oss.str() << std::endl; // Output: Hi Worl-???
// 4. Using std::ios::cur (from the current position)
oss.seekp(2, std::ios::cur); // Move 2 positions forward from the current position
oss << "+"; // Insert "+"
std::cout << oss.str() << std::endl; // Output: Hi Worl-?+??
return 0;
}
</div></li></ol></section><section class="chapter"><h5 id="4-2-2-input-stringstreams" data-toc="4-2-2-input-stringstreams">4.2.2 Input Stringstreams</h5><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_175"><p id="z7hbb6_181">Types matter! Stream stops reading at any whitespace or any invalid character for the type.</p></aside><p id="z7hbb6_176"><span id="z7hbb6_182"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-block" data-lang="cpp">
std::istringstream iss("16.9 Ounces");
double amount;
std::string unit;
iss >> amount >> unit; // amount = 16.9, unit = Ounces
std::istringstream iss("16.9 Ounces");
int amount;
std::string unit;
iss >> amount >> unit; // amount = 16, unit = ".9"
</div><p id="z7hbb6_178"><span id="z7hbb6_183"><font style="color:#8a2be2">Positioning Functions:</font></span></p><ol class="list _decimal" id="z7hbb6_179" type="1"><li class="list__item" id="z7hbb6_184"><p id="z7hbb6_186"><span id="z7hbb6_189"><font style="color:#ff00ff">tellg()</font></span></p><p id="z7hbb6_187">Returns the current position of the get pointer in the input string stream.</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <sstream>
int main() {
std::istringstream iss("Hello World");
iss >> std::ws; // Skip leading whitespaces
std::cout << "Current position: " << iss.tellg() << std::endl; // Output: 0
std::string word;
iss >> word; // Read "Hello"
std::cout << "Current position after reading 'Hello': " << iss.tellg() <<
std::endl; // Output: 5 (or 6 if there's a space after Hello)
return 0;
}
</div></li><li class="list__item" id="z7hbb6_185"><p id="z7hbb6_190"><span id="z7hbb6_194"><font style="color:#ff00ff">seekg(pos)</font></span></p><p id="z7hbb6_191">Moves the put pointer to a specific position within the output string stream.</p><p id="z7hbb6_192">The position can be an absolute offset from the beginning of the stream, or a relative offset from the current position (using std::ios::beg, std::ios::cur, or std::ios::end as a second argument).</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <sstream>
int main() {
std::istringstream iss("Hello World");
// Using absolute position from the beginning
iss.seekg(7); // Move to the 7th position from the beginning (equivalent to iss.seekg(7, std::ios::beg))
char char1;
iss.get(char1);
std::cout << "Character read after seeking to absolute position 7: " <<
char1 << std::endl; // Output: o
// Using ios::beg (beginning)
iss.seekg(6, std::ios::beg); // Move to the 6th position from the beginning
std::string word1;
iss >> word1;
std::cout << "Word read after seeking from beginning: " << word1 <<
std::endl; // Output: World
// Using ios::cur (current)
iss.seekg(2, std::ios::cur); // Move 2 positions forward from the current position (which is after "World")
char char2;
iss.get(char2);
std::cout << "Character read after seeking from current: " << char2 <<
std::endl; // Output: d
// Using ios::end (end)
iss.seekg(-5, std::ios::end); // Move 5 positions backward from the end
std::string word2;
iss >> word2;
std::cout << "Word read after seeking from end: " << word2 <<
std::endl; // Output: World
return 0;
}
</div></li></ol><aside class="prompt" data-type="tip" data-title="" id="z7hbb6_180"><p id="z7hbb6_195">Two data types:</p><ol class="list _decimal" id="z7hbb6_196" type="1"><li class="list__item" id="z7hbb6_199"><p id="z7hbb6_201"><span id="z7hbb6_202"><font style="color:#ff00ff">streampos:</font></span> Represents the position of the get pointer.</p></li><li class="list__item" id="z7hbb6_200"><p id="z7hbb6_203"><span id="z7hbb6_204"><font style="color:#ff00ff">streamoff:</font></span> Represents the difference (offset) between two streampos values.</p></li></ol><p id="z7hbb6_197"><span id="z7hbb6_205"><font style="color:#8a2be2">Example</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <sstream>
int main() {
// Create an output string stream
std::ostringstream oss;
oss << "Hello, world!";
// Get the current position using streampos
std::streampos pos = oss.tellp();
std::cout << "Current position in output stream: " << pos << std::endl; // Outputs: 13
// Move the position using streamoff
oss.seekp(5, std::ios::beg);
pos = oss.tellp();
std::cout << "New position in output stream after seekp: " << pos <<
std::endl; // Outputs: 5
// Create an input string stream with the data from the output stream
std::istringstream iss(oss.str());
// Get the current position using streampos
pos = iss.tellg();
std::cout << "Current position in input stream: " << pos << std::endl; //
Outputs: 0
// Move the position using streamoff
iss.seekg(7, std::ios::beg);
pos = iss.tellg();
std::cout << "New position in input stream after seekg: " << pos <<
std::endl; // Outputs: 7
return 0;
}
</div></aside></section><section class="chapter"><h5 id="4-2-3-getline" data-toc="4-2-3-getline">4.2.3 Getline</h5><div class="code-block" data-lang="cpp">
std::istream& getline(std::istream& is, std::string& str, char delim);
</div><ul class="list _bullet" id="z7hbb6_207"><li class="list__item" id="z7hbb6_211"><p id="z7hbb6_214"><span id="z7hbb6_215"><font style="color:#ff00ff">is:</font></span> The input stream from which to read.</p></li><li class="list__item" id="z7hbb6_212"><p id="z7hbb6_216"><span id="z7hbb6_217"><font style="color:#ff00ff">str:</font></span> The string where the read line will be stored.</p></li><li class="list__item" id="z7hbb6_213"><p id="z7hbb6_218"><span id="z7hbb6_219"><font style="color:#ff00ff">delim:</font></span> The delimiter character that specifies where to stop reading (optional, by default '\n').</p></li></ul><aside class="prompt" data-type="note" data-title="" id="z7hbb6_208"><p id="z7hbb6_220">getline() <span id="z7hbb6_221"><font style="color:#ff4500">consumes</font></span> the delim character!</p></aside><p id="z7hbb6_209"><span id="z7hbb6_222"><font style="color:#cd5c5c">Exampless</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="std::string input;">
std::string input;
std::cout << "Enter a line of text: ";
std::getline(std::cin, input);
std::cout << "You entered: " << input << std::endl;
</div></section><section class="chapter"><h5 id="4-2-4-state-bits" data-toc="4-2-4-state-bits">4.2.4 State Bits</h5><ol class="list _alpha-lower" id="z7hbb6_223" type="a"><li class="list__item" id="z7hbb6_227"><p id="z7hbb6_231"><span id="z7hbb6_232"><font style="color:#ff00ff">Good bit</font></span> - ready for read /write. (Nothing unusal, on when other bits are off)</p></li><li class="list__item" id="z7hbb6_228"><p id="z7hbb6_233"><span id="z7hbb6_234"><font style="color:#ff00ff">Fail bit</font></span> - previous operation failed, all future operations frozen. (Type mismatch, file can't be opened, seekg failed)</p></li><li class="list__item" id="z7hbb6_229"><p id="z7hbb6_235"><span id="z7hbb6_236"><font style="color:#ff00ff">EOF bit</font></span> - previous operation reached the end of buffer content (reached the end of buffer).</p></li><li class="list__item" id="z7hbb6_230"><p id="z7hbb6_237"><span id="z7hbb6_238"><font style="color:#ff00ff">Bad bit</font></span> - external error, like irrecoverable.(e.g. the file you are reading from suddenly is deleted)</p></li></ol><aside class="prompt" data-type="note" data-title="" id="z7hbb6_224"><p id="z7hbb6_239">Good and bad are not opposites! (e.g. type mismatch)</p><p id="z7hbb6_240">Good and fail are not opposites! (e.g. end of file)</p><p id="z7hbb6_241">Fail and EOF are normally the ones you will be checking.</p></aside><p id="z7hbb6_225"><span id="z7hbb6_242"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-block" data-lang="cpp">
std::istringstream iss("17");
int amount;
iss >> amount;
std::cout << (iss.eof() ? "EOF" : "Not EOF") << std::endl;
// There also exist iss.good(), iss.fail() & iss.bad()
</div></section></section><section class="chapter"><h4 id="4-3-input-streams" data-toc="4-3-input-streams">4.3 Input Streams</h4><p id="z7hbb6_243"><span id="z7hbb6_250"><font style="color:#8a2be2">There are four standard iostreams</font></span></p><ul class="list _bullet" id="z7hbb6_244"><li class="list__item" id="z7hbb6_251"><p id="z7hbb6_255"><span id="z7hbb6_256"><font style="color:#ff00ff">cout:</font></span> Standard Output Stream .</p></li><li class="list__item" id="z7hbb6_252"><p id="z7hbb6_257"><span id="z7hbb6_258"><font style="color:#ff00ff">cin:</font></span> Standard Input Stream (buffered).</p></li><li class="list__item" id="z7hbb6_253"><p id="z7hbb6_259"><span id="z7hbb6_260"><font style="color:#ff00ff">cerr (Standard Error Stream):</font></span> used to output errors (unbuffered).</p></li><li class="list__item" id="z7hbb6_254"><p id="z7hbb6_261"><span id="z7hbb6_262"><font style="color:#ff00ff">clog (Standard Logging Stream):</font></span> used for non-critical event logging (buffered).</p></li></ul><p id="z7hbb6_245"><span id="z7hbb6_263"><font style="color:#8a2be2">cin</font></span></p><ul class="list _bullet" id="z7hbb6_246"><li class="list__item" id="z7hbb6_264"><p id="z7hbb6_267">The program hangs and waits for user input when the position reaches EOF, past the last token in the buffer.</p></li><li class="list__item" id="z7hbb6_265"><p id="z7hbb6_268">The position pointer skips whitespace <span id="z7hbb6_269"><font style="color:#ff4500">after</font></span> the token with each >> operation.</p></li><li class="list__item" id="z7hbb6_266"><p id="z7hbb6_270">The position pointer does the following:</p><ul class="list _bullet" id="z7hbb6_271"><li class="list__item" id="z7hbb6_272"><p id="z7hbb6_274">consume all whitespaces (spaces, newlines, '\t', '\n', etc .)</p></li><li class="list__item" id="z7hbb6_273"><p id="z7hbb6_275">reads as many characters until:</p><ul class="list _bullet" id="z7hbb6_276"><li class="list__item" id="z7hbb6_277"><p id="z7hbb6_280">a whitespace is reached, or...</p></li><li class="list__item" id="z7hbb6_278"><p id="z7hbb6_281">for primitives, the maximum number of bytes necessary to form a valid variable.</p></li><li class="list__item" id="z7hbb6_279"><p id="z7hbb6_282">Example: if we extract an int from "86.2", we'll get 86, with pos at the decimal point.</p></li></ul></li></ul></li></ul><p id="z7hbb6_247"><span id="z7hbb6_283"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-comparer" id="z7hbb6_248" data-comparing="horizontally"><div class="code-block" data-lang="cpp" data-title="Example 1">
#include <iostream>
#include <string>
int main() {
double pi, r;
std::string name;
std::cin >> pi;
std::cin.ignore(); // ignore the newline character
std::getline(std::cin, name);
std::cin >> r;
std::cout << "Hello, " << name << "!" << std::endl;
std::cout << "Value of pi: " << pi << std::endl;
std::cout << "Value of r: " << r << std::endl;
return 0;
}
</div><div class="code-block" data-lang="cpp" data-title="Example 2">
#include <iostream>
#include <string>
int main() {
double pi, r;
std::string name;
std::cin >> pi;
std::getline(std::cin, name); // read '\n' from previous input
std::getline(std::cin, name); // read name
std::cin >> r;
std::cout << "Hello, " << name << "!" << std::endl;
std::cout << "Value of pi: " << pi << std::endl;
std::cout << "Value of r: " << r << std::endl;
return 0;
}
</div></div><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_249"><p id="z7hbb6_286">Don’t use getline() and std::cin() together, unless you really really have to!</p></aside></section><section class="chapter"><h4 id="4-4-output-streams" data-toc="4-4-output-streams">4.4 Output Streams</h4><p id="z7hbb6_287"><span id="z7hbb6_293"><font style="color:#8a2be2">cerr & clog</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
int main() {
std::cerr << "Error: Could not open the file!" << std::endl;
std::clog << "Log: User logged in successfully." << std::endl;
return 0;
}
</div><p id="z7hbb6_289"><span id="z7hbb6_294"><font style="color:#8a2be2">Input File Streams & Output File Streams</font></span></p><div class="table-wrapper"><table class="left_header wide" id="z7hbb6_290"><thead><tr class="ijRowHead" id="z7hbb6_295"><th id="z7hbb6_301"></th><th id="z7hbb6_302"><p>ifstream</p></th><th id="z7hbb6_303"><p>ofstream</p></th></tr></thead><tbody><tr id="z7hbb6_296"><th id="z7hbb6_304"><p>Purpose</p></th><td id="z7hbb6_305"><p>Input from a file</p></td><td id="z7hbb6_306"><p>Output to a file</p></td></tr><tr id="z7hbb6_297"><th id="z7hbb6_307"><p>Mode</p></th><td id="z7hbb6_308"><p>Opens a file in read mode</p></td><td id="z7hbb6_309"><p>Opens a file in write mode</p></td></tr><tr id="z7hbb6_298"><th id="z7hbb6_310"><p>Default behavior</p></th><td id="z7hbb6_311"><p>If the file doesn't exist, it fails to open.</p></td><td id="z7hbb6_312"><p>If the file doesn't exist, it creates a new one. If it exists, it overwrites the content by default.</p></td></tr><tr id="z7hbb6_299"><th id="z7hbb6_313"><p>Operators</p></th><td id="z7hbb6_314"><p>Primarily used with the extraction operator (>>) to read data from the file.</p></td><td id="z7hbb6_315"><p>Primarily used with the insertion operator (<<) to write data to the file.</p></td></tr><tr id="z7hbb6_300"><th id="z7hbb6_316"><p>Similarities</p></th><td id="z7hbb6_317" colspan="2"><ol class="list _alpha-lower" id="z7hbb6_318" type="a"><li class="list__item" id="z7hbb6_319"><p id="z7hbb6_321">They share many common methods like open(), close(), is_open() , good(), bad(), fail(), eof(), etc. for managing the file stream .</p></li><li class="list__item" id="z7hbb6_320"><p id="z7hbb6_322">Both inherit properties and methods from the base class fstream .</p></li></ol></td></tr></tbody></table></div><p id="z7hbb6_291"><span id="z7hbb6_323"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <fstream>
int main() {
// ifstream for reading from a file
std::ifstream inputFile("myInput.txt");
if (inputFile.is_open()) {
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
inputFile.close();
} else {
std::cerr << "Unable to open input file." << std::endl;
}
// ofstream for writing to a file
std::ofstream outputFile("myOutput.txt");
if (outputFile.is_open()) {
outputFile << "This is some text for the output file." << std::endl;
outputFile.close();
} else {
std::cerr << "Unable to open output file." << std::endl;
}
return 0;
}
</div></section></section><section class="chapter"><h3 id="5-modern-c-types" data-toc="5-modern-c-types">5 Modern C++ Types</h3><section class="chapter"><h4 id="5-1-auto" data-toc="5-1-auto">5.1 Auto</h4><ul class="list _bullet" id="z7hbb6_329"><li class="list__item" id="z7hbb6_331"><p id="z7hbb6_333">When a type name is too long and a simpler alias makes the code more readable, use it.</p></li><li class="list__item" id="z7hbb6_332"><p id="z7hbb6_334">In libraries there is a common name for a type within each class. Example:</p><ul class="list _bullet" id="z7hbb6_335"><li class="list__item" id="z7hbb6_336"><p id="z7hbb6_338">vector::iterator, map::iterator, string::iterator</p></li><li class="list__item" id="z7hbb6_337"><p id="z7hbb6_339">vector::reference, map::reference, string::reference</p></li></ul></li></ul><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_330"><p id="z7hbb6_340">Auto discards const and references!</p></aside></section><section class="chapter"><h4 id="5-2-pair-tuple" data-toc="5-2-pair-tuple">5.2 Pair/Tuple</h4><p id="z7hbb6_341">A pair is simply two objects bundled together.</p><aside class="prompt" data-type="note" data-title="" id="z7hbb6_342"><p id="z7hbb6_345">Remember to include < utility > and < tuple ></p></aside><p id="z7hbb6_343"><span id="z7hbb6_346"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="std::pair<double, int> price(3.4, 5);">
std::pair<double, int> price(3.4, 5);
// make_pair/tuple (C++ 11) automatically deduces the type!
auto prices = std::make_pair(3.4, 5);
auto values = std::make_tuple(3, 4, "hi");
// access via get/set
prices.first = prices.second; // prices = {5, 5}
get<0>(values) = get<1>(values); // values = {4, 4, "hi"}
// structured binding (C++ 17) - extract each binding
auto [a, b] = prices; // a = 5, b = 5
const auto& [c, d, e] = values; // c = 4, d = 4, e = "hi"
</div></section><section class="chapter"><h4 id="5-3-conversions" data-toc="5-3-conversions">5.3 Conversions</h4><p id="z7hbb6_347"><span id="z7hbb6_350"><font style="color:#cd5c5c">Exampless</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="int v1 = static_cast<double>(3.14); // v1 = 3">
int v1 = static_cast<double>(3.14); // v1 = 3
</div><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="const int v3 = 3;">
const int v3 = 3;
int* v4 = const_cast<int*> (&v3); // v4 = 3
</div></section><section class="chapter"><h4 id="5-4-initializer-list" data-toc="5-4-initializer-list">5.4 initializer_list</h4><p id="z7hbb6_351"><span id="z7hbb6_356"><font style="color:#8a2be2">Definition</font></span>: An initializer list is a lightweight vector that can be used as a parameter.</p><p id="z7hbb6_352"><span id="z7hbb6_357"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <vector>
#include <initializer_list>
class MyContainer {
private:
std::vector<int> data;
public:
// Constructor using initializer_list
MyContainer(std::initializer_list<int> values) {
// Iterate through the initializer_list and populate the vector
for (int value : values) {
data.push_back(value);
}
}
void print() const {
for (int value : data) {
std::cout << value << " ";
}
std::cout << std::endl;
}
};
int main() {
// Using initializer_list to initialize MyContainer
MyContainer container1 = {1, 2, 3, 4, 5};
container1.print();
MyContainer container2{6, 7, 8};
container2.print();
return 0;
}
</div><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_354"><p id="z7hbb6_358">C++ 11 provides a uniform initialization syntax. Using the uniform initialization syntax, the initializer list constructor is preferred over constructor.</p></aside><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="std::vector<int> v1(3, 10) // v1 = {10, 10, 10}">
std::vector<int> v1(3, 10) // v1 = {10, 10, 10}
std::vector<int> v2{3, 10} // v2 = {3, 10}
</div></section><section class="chapter"><h4 id="5-5-using" data-toc="5-5-using">5.5 using</h4><p id="z7hbb6_359">Create type aliases with the using keyword.</p><div class="code-comparer" id="z7hbb6_360" data-comparing="horizontally"><div class="code-block" data-lang="cpp" data-title="Types">
std::pair<bool, std::pair<double, double>>;
</div><div class="code-block" data-lang="cpp" data-title="Using keyword">
using Zeros = std::pair<double, double>;
using Solution = std::pair<bool, Zeros>;
</div></div></section></section></section><section class="chapter"><h2 id="standard-template-library-stl" data-toc="standard-template-library-stl">Ⅱ Standard Template Library (STL)</h2><p id="z7hbb6_364">The <span id="z7hbb6_370"><font style="color:#ff8c00">Standard Template Library (STL)</font></span> is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called algorithms, containers, functions, and iterators.</p><p id="z7hbb6_365">The <span id="z7hbb6_371"><font style="color:#ff8c00">C++ Standard Library</font></span> is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself.</p><aside class="prompt" data-type="note" data-title="" id="z7hbb6_366"><p id="z7hbb6_372">The STL and the C++ Standard Library are two distinct entities.</p><p id="z7hbb6_373">However, due to the popular use of "STL" and "Standard Template Library" in search engines, we occasionally use those names to make it easier to find our documentation.</p><p id="z7hbb6_374">In this documentation, Standard Template Library (STL) refers to the C++ Standard Library as a whole.</p></aside><section class="chapter"><h3 id="6-containers" data-toc="6-containers">6 Containers</h3><section class="chapter"><h4 id="6-1-sequence-containers" data-toc="6-1-sequence-containers">6.1 Sequence Containers</h4><p id="z7hbb6_379"><span id="z7hbb6_383"><font style="color:#ff8c00">Sequence Containers:</font></span> Containers which provide access to a linear sequence of elements.</p><ul class="list _bullet" id="z7hbb6_380"><li class="list__item" id="z7hbb6_384"><p id="z7hbb6_389"><code class="code" id="z7hbb6_390">std::vector<T></code></p></li><li class="list__item" id="z7hbb6_385"><p id="z7hbb6_391"><code class="code" id="z7hbb6_392">std::deque<T></code></p></li><li class="list__item" id="z7hbb6_386"><p id="z7hbb6_393"><code class="code" id="z7hbb6_394">std::array<T></code></p></li><li class="list__item" id="z7hbb6_387"><p id="z7hbb6_395"><code class="code" id="z7hbb6_396">std::list<T></code></p></li><li class="list__item" id="z7hbb6_388"><p id="z7hbb6_397"><code class="code" id="z7hbb6_398">std::forward_list<T></code></p></li></ul><section class="chapter"><h5 id="6-1-1-vector" data-toc="6-1-1-vector">6.1.1 Vector</h5><p id="z7hbb6_399"><span id="z7hbb6_408"><font style="color:#ff8c00">Vector:</font></span> An array with changeable size.</p><p id="z7hbb6_400"><span id="z7hbb6_409"><font style="color:#8a2be2">Example</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec; // Create an empty vector
std::vector<int> vec2(5); // Create a vector with 5 copies of 0
std::vector<int> vec3{5, 1}; // Create a vector with 5 copies of value 1
vec.push_back(1); // Add 1 to the end of the vector
vec.clear(); // Clear vector
if (vec.empty()) { // Check if vector is empty
std::cout << "Vector is empty" << std::endl;
}
int k = vec2[0]; // Get the element of index 0
int l = vec2.at(0); // Get the element of index 0
vec2.at(0) = 2; // Replace the element at index 0
vec2[0] = 2; // Replace the element at index 0
return 0;
}
</div><div class="table-wrapper"><table class="left_header wide" id="z7hbb6_402"><thead><tr class="ijRowHead" id="z7hbb6_410"><th id="z7hbb6_413"></th><th id="z7hbb6_414"><p><code class="code" id="z7hbb6_416">vec[index]</code></p></th><th id="z7hbb6_415"><p><code class="code" id="z7hbb6_417">vec.at(index)</code></p></th></tr></thead><tbody><tr id="z7hbb6_411"><th id="z7hbb6_418"><p>Bounds Checking</p></th><td id="z7hbb6_419"><p>No</p></td><td id="z7hbb6_420"><p>Yes</p></td></tr><tr id="z7hbb6_412"><th id="z7hbb6_421"><p>Speed</p></th><td id="z7hbb6_422"><p>Fast</p></td><td id="z7hbb6_423"><p>Slow</p></td></tr></tbody></table></div><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_403"><p id="z7hbb6_424">If you write your program <span id="z7hbb6_425"><font style="color:#adff2f">correctly</font></span>, bounds checking will just <span id="z7hbb6_426"><font style="color:#ff4500">slow</font></span> you down.</p></aside><p id="z7hbb6_404"><span id="z7hbb6_427"><font style="color:#8a2be2">Advantages:</font></span></p><ul class="list _bullet" id="z7hbb6_405"><li class="list__item" id="z7hbb6_428"><p id="z7hbb6_430">Fast, lightweight & intuitive.</p></li><li class="list__item" id="z7hbb6_429"><p id="z7hbb6_431">Grow efficiently <span id="z7hbb6_432"><font style="color:#adff2f">in one direction</font></span>.</p></li></ul><p id="z7hbb6_406"><span id="z7hbb6_433"><font style="color:#8a2be2">Disadvantages:</font></span></p><ul class="list _bullet" id="z7hbb6_407"><li class="list__item" id="z7hbb6_434"><p id="z7hbb6_435">cannot push_front!</p></li></ul></section><section class="chapter"><h5 id="6-1-2-deque" data-toc="6-1-2-deque">6.1.2 Deque</h5><p id="z7hbb6_436"><span id="z7hbb6_444"><font style="color:#ff8c00">Deque:</font></span> A deque is a doubly ended queue.</p><p id="z7hbb6_437"><span id="z7hbb6_445"><font style="color:#8a2be2">Implementation</font></span></p><p id="z7hbb6_438">Instead of storing all elements in a single contiguous block, deque internally manages a collection of fixed-size arrays called "chunks" or "buffers." => separate subarrays and allocated independently</p><p id="z7hbb6_439">Deque maintains a dynamic array (usually a small array or a tree-like structure) called a "map" or "central index". This map stores pointers to the beginning of each chunk.</p><p id="z7hbb6_440"><span id="z7hbb6_446"><font style="color:#8a2be2">Advantages:</font></span></p><ul class="list _bullet" id="z7hbb6_441"><li class="list__item" id="z7hbb6_447"><p id="z7hbb6_448">Can push_front!</p></li></ul><p id="z7hbb6_442"><span id="z7hbb6_449"><font style="color:#8a2be2">Disadvantages:</font></span></p><ul class="list _bullet" id="z7hbb6_443"><li class="list__item" id="z7hbb6_450"><p id="z7hbb6_451">For other operations, vector outperform deque.</p></li></ul></section></section><section class="chapter"><h4 id="6-2-container-adapters" data-toc="6-2-container-adapters">6.2 Container Adapters</h4><ol class="list _alpha-lower" id="z7hbb6_452" type="a"><li class="list__item" id="z7hbb6_453"><p id="z7hbb6_455"><span id="z7hbb6_457"><font style="color:#ff00ff">Stacks:</font></span></p><ul class="list _bullet" id="z7hbb6_456"><li class="list__item" id="z7hbb6_458"><p id="z7hbb6_460">The standard containers <code class="code" id="z7hbb6_461">std::vector</code>, <code class="code" id="z7hbb6_462">std::deque</code>, <code class="code" id="z7hbb6_463">std::list</code> satisfy these requirements.</p></li><li class="list__item" id="z7hbb6_459"><p id="z7hbb6_464">Just limit the functionality of a vector/deque to only allow <code class="code" id="z7hbb6_465">push_back</code> and <code class="code" id="z7hbb6_466">pop_back</code>.</p></li></ul></li><li class="list__item" id="z7hbb6_454"><p id="z7hbb6_467"><span id="z7hbb6_469"><font style="color:#ff00ff">Queues:</font></span></p><ul class="list _bullet" id="z7hbb6_468"><li class="list__item" id="z7hbb6_470"><p id="z7hbb6_472">The standard containers <code class="code" id="z7hbb6_473">std::deque</code> and <code class="code" id="z7hbb6_474">std::list</code> satisfy these requirements.</p></li><li class="list__item" id="z7hbb6_471"><p id="z7hbb6_475">Just limit the functionality of a deque to only allow <code class="code" id="z7hbb6_476">push_back</code> and <code class="code" id="z7hbb6_477">pop_front</code>.</p></li></ul></li></ol></section><section class="chapter"><h4 id="6-3-associative-containers" data-toc="6-3-associative-containers">6.3 Associative Containers</h4><p id="z7hbb6_478"><span id="z7hbb6_480"><font style="color:#ff8c00">Associative containers:</font></span> Data is accessed using the <span id="z7hbb6_481"><font style="color:#ff4500">key</font></span> instead of index.</p><style>.theme-dark .plantuml > svg {filter: hue-rotate(180deg) invert(0.9);}div.plantuml {overflow-x: auto;}</style><div class="plantuml"><?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="256px" preserveAspectRatio="none" style="width:770px;height:256px;background:#FFFFFF;" version="1.1" viewBox="0 0 770 256" width="770px" zoomAndPan="magnify"><defs/><g><rect fill="#F1F1F1" height="38.6211" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="125" x="10" y="107.9316"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="105" x="20" y="133.0391">Class Templates</text><rect fill="#F1F1F1" height="57.2422" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="309" x="185" y="40"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="223" x="199" y="65.1074">Based on ordering property of keys</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="289" x="195" y="83.7285">Keys need to be comparable using < operator</text><rect fill="#F1F1F1" height="38.6211" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="132" x="544" y="20"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="112" x="554" y="45.1074">std::map<T1, T2></text><path d="M494,68.6211 L504,68.6211 C519,68.6211 519,39.3105 534,39.3105 L544,39.3105 " fill="none" style="stroke:#181818;stroke-width:1.0;"/><rect fill="#F1F1F1" height="38.6211" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="91" x="544" y="78.6211"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="71" x="554" y="103.7285">std::set<T></text><path d="M494,68.6211 L504,68.6211 C519,68.6211 519,97.9316 534,97.9316 L544,97.9316 " fill="none" style="stroke:#181818;stroke-width:1.0;"/><path d="M135,127.2422 L145,127.2422 C160,127.2422 160,68.6211 175,68.6211 L185,68.6211 " fill="none" style="stroke:#181818;stroke-width:1.0;"/><rect fill="#F1F1F1" height="57.2422" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="317" x="185" y="157.2422"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="149" x="199" y="182.3496">Based on hash function</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="297" x="195" y="200.9707">You need to define how the key can be hashed</text><rect fill="#F1F1F1" height="38.6211" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="206" x="552" y="137.2422"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="186" x="562" y="162.3496">std::unordered_map<T1, T2></text><path d="M502,185.8633 L512,185.8633 C527,185.8633 527,156.5527 542,156.5527 L552,156.5527 " fill="none" style="stroke:#181818;stroke-width:1.0;"/><rect fill="#F1F1F1" height="38.6211" rx="12.5" ry="12.5" style="stroke:#181818;stroke-width:1.5;" width="165" x="552" y="195.8633"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="145" x="562" y="220.9707">std::unordered_set<T></text><path d="M502,185.8633 L512,185.8633 C527,185.8633 527,215.1738 542,215.1738 L552,215.1738 " fill="none" style="stroke:#181818;stroke-width:1.0;"/><path d="M135,127.2422 L145,127.2422 C160,127.2422 160,185.8633 175,185.8633 L185,185.8633 " fill="none" style="stroke:#181818;stroke-width:1.0;"/><!--SRC=[RP11Jm8n48Nl_HNl24ICh6Xq9SQ8aeWYHXOIJwPi1xPnjzsqKmp-Uhi6HHClFSpCU-_hk_8i7LVQg4hMeeDXARr7HbLTIYOlEfqKrzAJWZMmJf7JPetQsPeSRs5NUAEj5_VnWQ5unXPBGcwhMZgvB0d1Due16eLawowYPmUULPh6o47MEq2MNEw7ddYGNVuDBgGli0ecPssDUB7X9qlHIXj2OT_11JKmoALf41eDgLzfmNpnathzDtU_tX5SKInbLunuAgNX-UG16t8-Gg1tc1mbnuUzf3Lo6jESaHmXwQNzy_IaZ-4iGxDlYzRaBeEtmUK4fJqxlGpDBzfYB3SIpy6mhYZ5j2Oplhd_7k3MRBIpfYB3OhoOx0zE-zrhpPYHYoXOJCGDhMGeEIfogsBNAURPg7ic7gHP1xcEtX-56DhewxOfXe-V]--></g></svg></div></section><section class="chapter"><h4 id="iterators" data-toc="iterators">6.4 Iterators</h4><p id="z7hbb6_482"><span id="z7hbb6_492"><font style="color:#8a2be2">Four iterator operations:</font></span></p><ul class="list _bullet" id="z7hbb6_483"><li class="list__item" id="z7hbb6_493"><p id="z7hbb6_497"><span id="z7hbb6_499"><font style="color:#ff00ff">Create iterator:</font></span></p><p id="z7hbb6_498"><code class="code" id="z7hbb6_500">std::set<int>::iterator iter = mySet.begin()</code></p></li><li class="list__item" id="z7hbb6_494"><p id="z7hbb6_501"><span id="z7hbb6_503"><font style="color:#ff00ff">Dereference iterator to read value currently pointed to:</font></span></p><p id="z7hbb6_502"><code class="code" id="z7hbb6_504">int val = *iter</code></p></li><li class="list__item" id="z7hbb6_495"><p id="z7hbb6_505"><span id="z7hbb6_507"><font style="color:#ff00ff">Advance iterator:</font></span></p><p id="z7hbb6_506"><code class="code" id="z7hbb6_508">iter++</code>; or <code class="code" id="z7hbb6_509">++iter</code></p></li><li class="list__item" id="z7hbb6_496"><p id="z7hbb6_510"><span id="z7hbb6_511"><font style="color:#ff00ff">Compare against another iterator</font></span> (especially <code class="code" id="z7hbb6_512">.end()</code> iterator)</p></li></ul><p id="z7hbb6_484"><span id="z7hbb6_513"><font style="color:#8a2be2">Map Iterators:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="std::map<int, int> m;">
std::map<int, int> m;
std::map<int, int>::iterator i = m.begin();
std::map<int, int>::iterator end = m.end();
while (i != end) {
std::cout << (*i).first << " " << (*i).second << std::endl;
i++;
}
</div><svg aria-roledescription="stateDiagram" role="graphics-document document" viewBox="0 0 543.390625 146" style="max-width: 543.390625px;" class="statediagram" xmlns="http://www.w3.org/2000/svg" width="100%" id="mermaid"><g><defs><marker orient="auto" markerUnits="userSpaceOnUse" markerHeight="14" markerWidth="20" refY="7" refX="19" id="mermaid_stateDiagram-barbEnd"><path d="M 19,7 L9,13 L14,7 L9,1 Z"></path></marker></defs><g class="root"><g class="clusters"></g><g class="edgePaths"><path marker-end="url(#mermaid_stateDiagram-barbEnd)" style=";fill:none" class="edge-thickness-normal edge-pattern-solid transition" id="edge0" d="M136.906,73L141.073,73C145.24,73,153.573,73,159.823,73C166.073,73,170.24,73,174.406,73C178.573,73,182.74,73,184.823,73L186.906,73"></path><path marker-end="url(#mermaid_stateDiagram-barbEnd)" style=";fill:none" class="edge-thickness-normal edge-pattern-solid transition" id="edge1" d="M294.547,73L298.714,73C302.88,73,311.214,73,317.464,73C323.714,73,327.88,73,332.047,73C336.214,73,340.38,73,342.464,73L344.547,73"></path><path marker-end="url(#mermaid_stateDiagram-barbEnd)" style=";fill:none" class="edge-thickness-normal edge-pattern-solid transition" id="edge2" d="M409.701,53L415.48,48.833C421.259,44.667,432.817,36.333,441.208,32.167C449.599,28,454.823,28,460.047,28C465.271,28,470.495,28,473.107,28L475.719,28"></path><path marker-end="url(#mermaid_stateDiagram-barbEnd)" style=";fill:none" class="edge-thickness-normal edge-pattern-solid transition" id="edge3" d="M409.701,93L415.48,97.167C421.259,101.333,432.817,109.667,440.679,113.833C448.542,118,452.708,118,456.875,118C461.042,118,465.208,118,467.292,118L469.375,118"></path></g><g class="edgeLabels"><g class="edgeLabel"><g transform="translate(0, 0)" class="label"><foreignObject height="0" width="0"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" class="labelBkg" xmlns="http://www.w3.org/1999/xhtml"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g transform="translate(0, 0)" class="label"><foreignObject height="0" width="0"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" class="labelBkg" xmlns="http://www.w3.org/1999/xhtml"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g transform="translate(0, 0)" class="label"><foreignObject height="0" width="0"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" class="labelBkg" xmlns="http://www.w3.org/1999/xhtml"><span class="edgeLabel"></span></div></foreignObject></g></g><g class="edgeLabel"><g transform="translate(0, 0)" class="label"><foreignObject height="0" width="0"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" class="labelBkg" xmlns="http://www.w3.org/1999/xhtml"><span class="edgeLabel"></span></div></foreignObject></g></g></g><g class="nodes"><g transform="translate(72.453125, 73)" id="state-Random_Access-0" class="node statediagram-state"><rect height="40" width="128.90625" y="-20" x="-64.453125" ry="5" data-et="node" data-id="abc" rx="5" style="" class="basic label-container"></rect><g transform="translate(-56.453125, -12)" style="" class="label"><rect></rect><foreignObject height="24" width="112.90625"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" xmlns="http://www.w3.org/1999/xhtml"><span class="nodeLabel"><p>Random_Access</p></span></div></foreignObject></g></g><g transform="translate(240.7265625, 73)" id="state-Bidirectional-1" class="node statediagram-state"><rect height="40" width="107.640625" y="-20" x="-53.8203125" ry="5" data-et="node" data-id="abc" rx="5" style="" class="basic label-container"></rect><g transform="translate(-45.8203125, -12)" style="" class="label"><rect></rect><foreignObject height="24" width="91.640625"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" xmlns="http://www.w3.org/1999/xhtml"><span class="nodeLabel"><p>Bidirectional</p></span></div></foreignObject></g></g><g transform="translate(381.9609375, 73)" id="state-Forward-3" class="node statediagram-state"><rect height="40" width="74.828125" y="-20" x="-37.4140625" ry="5" data-et="node" data-id="abc" rx="5" style="" class="basic label-container"></rect><g transform="translate(-29.4140625, -12)" style="" class="label"><rect></rect><foreignObject height="24" width="58.828125"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" xmlns="http://www.w3.org/1999/xhtml"><span class="nodeLabel"><p>Forward</p></span></div></foreignObject></g></g><g transform="translate(502.3828125, 28)" id="state-Input-2" class="node statediagram-state"><rect height="40" width="53.328125" y="-20" x="-26.6640625" ry="5" data-et="node" data-id="abc" rx="5" style="" class="basic label-container"></rect><g transform="translate(-18.6640625, -12)" style="" class="label"><rect></rect><foreignObject height="24" width="37.328125"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" xmlns="http://www.w3.org/1999/xhtml"><span class="nodeLabel"><p>Input</p></span></div></foreignObject></g></g><g transform="translate(502.3828125, 118)" id="state-Output-3" class="node statediagram-state"><rect height="40" width="66.015625" y="-20" x="-33.0078125" ry="5" data-et="node" data-id="abc" rx="5" style="" class="basic label-container"></rect><g transform="translate(-25.0078125, -12)" style="" class="label"><rect></rect><foreignObject height="24" width="50.015625"><div style="display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;" xmlns="http://www.w3.org/1999/xhtml"><span class="nodeLabel"><p>Output</p></span></div></foreignObject></g></g></g></g></g></svg><section class="chapter"><h5 id="6-4-1-input-iterators" data-toc="6-4-1-input-iterators">6.4.1 Input Iterators</h5><p id="z7hbb6_514">For sequential, single-pass input.</p><p id="z7hbb6_515">Read only, i.e. can only be dereferenced on <span id="z7hbb6_518"><font style="color:#ff4500">right</font></span> side of expression.</p><p id="z7hbb6_516"><span id="z7hbb6_519"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="vector<int>::iterator iter = myVector.begin();">
vector<int>::iterator iter = myVector.begin();
int val = *iter;
</div></section><section class="chapter"><h5 id="6-4-2-output-iterators" data-toc="6-4-2-output-iterators">6.4.2 Output Iterators</h5><p id="z7hbb6_520">For sequential, single-pass output.</p><p id="z7hbb6_521">Read only, i.e. can only be dereferenced on <span id="z7hbb6_524"><font style="color:#ff4500">left</font></span> side of expression.</p><p id="z7hbb6_522"><span id="z7hbb6_525"><font style="color:#8a2be2">Example:</font></span></p><div class="code-block" data-lang="cpp">
vector<int>::iterator iter = myVector.begin();
*iter = 5;
</div></section><section class="chapter"><h5 id="6-4-3-forward-iterators" data-toc="6-4-3-forward-iterators">6.4.3 Forward Iterators</h5><p id="z7hbb6_526">Combines input and output, plus can make multiple passes.</p><p id="z7hbb6_527">Can read from and write to (if not const iterator).</p><p id="z7hbb6_528"><span id="z7hbb6_530"><font style="color:#8a2be2">Example:</font></span></p><div class="code-block" data-lang="cpp">
// multiple passes
vector<int>::iterator iter1 = myVector.begin();
vector<int>::iterator iter2 = myVector.begin();
iter1++;
iter2++;
if (iter1 == iter2) { cout << "Equal" << endl; } // Equal
</div></section><section class="chapter"><h5 id="6-4-4-bidirectional-iterators" data-toc="6-4-4-bidirectional-iterators">6.4.4 Bidirectional Iterators</h5><p id="z7hbb6_531">Same as forward iterators, plus can go backwards with the decrement operator (--).</p><p id="z7hbb6_532"><span id="z7hbb6_533"><font style="color:#8a2be2">Use cases:</font></span> <code class="code" id="z7hbb6_534">std::map</code>, <code class="code" id="z7hbb6_535">std::set</code>, <code class="code" id="z7hbb6_536">std::list</code></p></section><section class="chapter"><h5 id="6-4-5-random-access-iterators" data-toc="6-4-5-random-access-iterators">6.4.5 Random Access Iterators</h5><p id="z7hbb6_537">Same as bidirectional iterators, plus can be implemented or decremented by arbitrary amounts using + and -.</p><p id="z7hbb6_538"><span id="z7hbb6_539"><font style="color:#8a2be2">Use cases:</font></span> <code class="code" id="z7hbb6_540">std::vector</code>, <code class="code" id="z7hbb6_541">std::deque</code>, <code class="code" id="z7hbb6_542">std::string</code></p></section></section></section><section class="chapter"><h3 id="7-templates" data-toc="7-templates">7 Templates</h3><section class="chapter"><h4 id="7-1-template-functions" data-toc="7-1-template-functions">7.1 Template Functions</h4><p id="z7hbb6_545"><span id="z7hbb6_557"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-block" data-lang="cpp">
template <typename T>
std::pair<T, T> my_minmax(T a, T b) {
if (a < b) return {a, b};
else return {b, a};
}
</div><p id="z7hbb6_547">The following code:</p><div class="code-block" data-lang="cpp">
my_minmax(cout, cout);
</div><p id="z7hbb6_549"><span id="z7hbb6_558"><font style="color:#ff00ff">Semantic error:</font></span> you can’t call operator < on two streams.</p><p id="z7hbb6_550"><span id="z7hbb6_559"><font style="color:#ff00ff">Conceptual error:</font></span> you can’t find the min or max of two streams.</p><p id="z7hbb6_551">The compiler deduces the types and literally replaces the types. Compiler will produce semantic errors, not conceptual error.</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="template <typename Collection, typename DataType>">
template <typename Collection, typename DataType>
int countOccurences(const Collection& list, DataType val) {
int count = 0;
for (size_t i = 0; i < list.size(); ++i) {
if (list[i] == val) ++count;
}
return count;
}
</div><p id="z7hbb6_553">Problem lies in indexing <code class="code" id="z7hbb6_560">list[i]</code>.</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="template <typename Collection, typename DataType>">
template <typename Collection, typename DataType>
int countOccurences(const Collection& list, DataType val) {
int count = 0;
for (auto iter = list.begin(); iter != list.end(); ++iter) {
if (*iter == val) ++count;
}
return count;
}
</div><p id="z7hbb6_555">Or:</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="template <typename Collection, typename DataType>">
template <typename Collection, typename DataType>
int countOccurences(const Collection& collection, const DataType& val) {
int count = 0;
for (const auto& element : collection) {
if (element == val) {
++count;
}
}
return count;
}
</div></section><section class="chapter"><h4 id="7-2-template-classes" data-toc="7-2-template-classes">7.2 Template Classes</h4><section class="procedure-steps"><h3 id="template-class" data-toc="template-class">Template Class</h3><ol class="list _decimal"><li class="list__item" id="z7hbb6_562"><p id="z7hbb6_566">Add template declaration for class</p></li><li class="list__item" id="z7hbb6_563"><p id="z7hbb6_567">Add all the member type aliases</p></li><li class="list__item" id="z7hbb6_564"><p id="z7hbb6_568">Add the template declaration to every single class member</p></li><li class="list__item" id="z7hbb6_565"><p id="z7hbb6_569">Move everything to the .h file => separate compilation template classes are not classes themselves</p></li></ol></section></section></section><section class="chapter"><h3 id="8-functions-and-algorithms" data-toc="8-functions-and-algorithms">8 Functions and Algorithms</h3><section class="chapter"><h4 id="Lambda" data-toc="Lambda">8.1 Lambda Functions</h4><div class="code-block" data-lang="cpp">
auto isLessThanLimit = [limit](auto val) -> bool {
return val < limit;
};
</div><ul class="list _bullet" id="z7hbb6_573"><li class="list__item" id="z7hbb6_581"><p id="z7hbb6_585"><code class="code" id="z7hbb6_586">auto</code>: We don't know the type, ask compiler.</p></li><li class="list__item" id="z7hbb6_582"><p id="z7hbb6_587"><code class="code" id="z7hbb6_588">[limit]</code>: Capture clause, gives access to outside variables.</p></li><li class="list__item" id="z7hbb6_583"><p id="z7hbb6_589"><code class="code" id="z7hbb6_590">(auto)</code>: Parameter list, can use auto!</p></li><li class="list__item" id="z7hbb6_584"><p id="z7hbb6_591"><code class="code" id="z7hbb6_592">-> bool</code>: Return type, optional.</p></li></ul><p id="z7hbb6_574">Two types of capture clause: By reference or by value.</p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="// capture all by value, except teas is by reference">
// capture all by value, except teas is by reference
auto func1 = [=, &teas](parameters) -> return-value {
// body
};
// capture all by reference, except banned is by value
auto func2 = [&, banned](parameters) -> return-value {
// body
};
</div><aside class="prompt" data-type="tip" data-title="" id="z7hbb6_576"><p id="z7hbb6_593"><code class="code" id="z7hbb6_598">std::function<R(Args…)></code> is a generic wrapper for all things callable.</p><div class="code-block" data-lang="cpp">
int add(int a, int b) {
return a + b;
}
int main() {
std::function<int(int, int)> func; // initially empty
func = add; // Assign a regular function
std::cout << func(2, 3) << std::endl; // Output: 5
func = [](int a, int b) { return a * b; }; // Reassign a lambda
std::cout << func(2, 3) << std::endl; // Output: 6
return 0;
}
</div><p id="z7hbb6_595">In this context, <code class="code" id="z7hbb6_599">std::function<int(int, int)></code> can store any callable object as long as it matches the signature.</p><p id="z7hbb6_596"><span id="z7hbb6_600"><font style="color:#8a2be2">Benefit:</font></span></p><ol class="list _alpha-lower" id="z7hbb6_597" type="a"><li class="list__item" id="z7hbb6_601"><p id="z7hbb6_603"><span id="z7hbb6_604"><font style="color:#ff00ff">Type Erasure for Flexibility:</font></span> It lets you work with different callable objects through a common interface. You can pass <code class="code" id="z7hbb6_605">std::function</code> objects to functions or store them in data structures without knowing the exact type of the underlying callable.</p></li><li class="list__item" id="z7hbb6_602"><p id="z7hbb6_606"><span id="z7hbb6_607"><font style="color:#ff00ff">Enables Polymorphism with Callables:</font></span> You can have a function that accepts a std::function as a parameter, allowing it to work with different lambda functions or other callable types at runtime.</p></li></ol></aside><p id="z7hbb6_577"><code class="code" id="z7hbb6_608">std::bind</code> adapts existing function objects to create new ones with specific argument values pre-filled.</p><div class="code-block" data-lang="cpp">
int multiplyAndAdd(int a, int b, int c) {
return (a * b) + c;
}
int main() {
auto operation = std::bind(multiplyAndAdd, std::placeholders::_1,
std::placeholders::_2, 4);
std::cout << operation(2, 3) << std::endl; // Output: 10 ((2*3) + 4)
}
</div><ul class="list _bullet" id="z7hbb6_579"><li class="list__item" id="z7hbb6_609"><p id="z7hbb6_612"><code class="code" id="z7hbb6_613">std::placeholders::_1</code> means "take the first argument passed to operation".</p></li><li class="list__item" id="z7hbb6_610"><p id="z7hbb6_614"><code class="code" id="z7hbb6_615">std::placeholders::_2</code> means "take the second argument passed to operation".</p></li><li class="list__item" id="z7hbb6_611"><p id="z7hbb6_616">4 is the third argument of <code class="code" id="z7hbb6_617">multiplyAndAdd</code>.</p></li></ul><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_580"><p id="z7hbb6_618">Lambdas provide a convenient and expressive way to define objects that behave like functions. => Lambdas are a type of function object.</p></aside></section><section class="chapter"><h4 id="8-2-algorithms" data-toc="8-2-algorithms">8.2 Algorithms</h4><section class="chapter"><h5 id="8-2-1-std-sort" data-toc="8-2-1-std-sort">8.2.1 std::sort</h5><p id="z7hbb6_624"><span id="z7hbb6_632"><font style="color:#8a2be2">Syntax:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <algorithm> // Required header">
#include <algorithm> // Required header
// 1. Basic Usage (Sorting using < operator)
template <class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last);
// 2. Custom Comparison Function
template <class RandomAccessIterator, class Compare>
void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
</div><p id="z7hbb6_626"><span id="z7hbb6_633"><font style="color:#8a2be2">Example:</font></span></p><div class="code-block" data-lang="cpp">
std::vector<int> numbers = {3, 1, 4, 1, 5};
std::sort(numbers.begin(), numbers.end()); // Sort the entire vector
std::sort(numbers.begin(), numbers.end(), std::greater<int>()); // Sort in descending order
</div><p id="z7hbb6_628"><span id="z7hbb6_634"><font style="color:#8a2be2">Parameters:</font></span></p><ol class="list _decimal" id="z7hbb6_629" type="1"><li class="list__item" id="z7hbb6_635"><p id="z7hbb6_638"><span id="z7hbb6_639"><font style="color:#ff00ff">first (iterator):</font></span> An iterator pointing to the beginning of the range you want to sort.</p></li><li class="list__item" id="z7hbb6_636"><p id="z7hbb6_640"><span id="z7hbb6_641"><font style="color:#ff00ff">last (iterator):</font></span> An iterator pointing to one position past the end of the range to be sorted.</p></li><li class="list__item" id="z7hbb6_637"><p id="z7hbb6_642"><span id="z7hbb6_643"><font style="color:#ff00ff">comp (comparison function) (optional):</font></span> A binary function (takes two arguments) that defines the sorting criterion. It should return true if the first argument should come before the second in the sorted order, and false otherwise.</p></li></ol><p id="z7hbb6_630"><span id="z7hbb6_644"><font style="color:#8a2be2">Important notes:</font></span></p><ul class="list _bullet" id="z7hbb6_631"><li class="list__item" id="z7hbb6_645"><p id="z7hbb6_648">You can sort a portion of the entire vector, array, etc.</p><div class="code-block" data-lang="cpp">
std::vector<int> data = {5, 2, 8, 1, 9, 3};
std::sort(data.begin(), data.begin() + 4); // Result: data = {1, 2, 5, 8, 9, 3}
</div></li><li class="list__item" id="z7hbb6_646"><p id="z7hbb6_650">You can overload operator < to define default sorting behavior.</p><div class="code-block" data-lang="cpp">
struct Item {
int id;
std::string name;
};
// Stable Comparison
bool compareByNameStable(const Item& a, const Item& b) {
if (a.name == b.name) {
return a.id < b.id; // Keep original order based on 'id' if names are equal
}
return a.name < b.name;
}
int main() {
std::vector<Item> items = {
{1, "Apple"},
{2, "Banana"},
{3, "Apple"}
};
std::sort(items.begin(), items.end(), compareByNameStable);
}
</div></li><li class="list__item" id="z7hbb6_647"><p id="z7hbb6_652"><span id="z7hbb6_653"><font style="color:#ff00ff">Average case:</font></span> <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="11.15ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 4928.3 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mi"><path data-c="1D442" d="M740 435Q740 320 676 213T511 42T304 -22Q207 -22 138 35T51 201Q50 209 50 244Q50 346 98 438T227 601Q351 704 476 704Q514 704 524 703Q621 689 680 617T740 435ZM637 476Q637 565 591 615T476 665Q396 665 322 605Q242 542 200 428T157 216Q157 126 200 73T314 19Q404 19 485 98T608 313Q637 408 637 476Z"></path></g><g data-mml-node="mo" transform="translate(763,0)"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mi" transform="translate(1152,0)"><path data-c="1D441" d="M234 637Q231 637 226 637Q201 637 196 638T191 649Q191 676 202 682Q204 683 299 683Q376 683 387 683T401 677Q612 181 616 168L670 381Q723 592 723 606Q723 633 659 637Q635 637 635 648Q635 650 637 660Q641 676 643 679T653 683Q656 683 684 682T767 680Q817 680 843 681T873 682Q888 682 888 672Q888 650 880 642Q878 637 858 637Q787 633 769 597L620 7Q618 0 599 0Q585 0 582 2Q579 5 453 305L326 604L261 344Q196 88 196 79Q201 46 268 46H278Q284 41 284 38T282 19Q278 6 272 0H259Q228 2 151 2Q123 2 100 2T63 2T46 1Q31 1 31 10Q31 14 34 26T39 40Q41 46 62 46Q130 49 150 85Q154 91 221 362L289 634Q287 635 234 637Z"></path></g><g data-mml-node="mi" transform="translate(2206.7,0)"><path data-c="6C" d="M42 46H56Q95 46 103 60V68Q103 77 103 91T103 124T104 167T104 217T104 272T104 329Q104 366 104 407T104 482T104 542T103 586T103 603Q100 622 89 628T44 637H26V660Q26 683 28 683L38 684Q48 685 67 686T104 688Q121 689 141 690T171 693T182 694H185V379Q185 62 186 60Q190 52 198 49Q219 46 247 46H263V0H255L232 1Q209 2 183 2T145 3T107 3T57 1L34 0H26V46H42Z"></path><path data-c="6F" d="M28 214Q28 309 93 378T250 448Q340 448 405 380T471 215Q471 120 407 55T250 -10Q153 -10 91 57T28 214ZM250 30Q372 30 372 193V225V250Q372 272 371 288T364 326T348 362T317 390T268 410Q263 411 252 411Q222 411 195 399Q152 377 139 338T126 246V226Q126 130 145 91Q177 30 250 30Z" transform="translate(278,0)"></path><path data-c="67" d="M329 409Q373 453 429 453Q459 453 472 434T485 396Q485 382 476 371T449 360Q416 360 412 390Q410 404 415 411Q415 412 416 414V415Q388 412 363 393Q355 388 355 386Q355 385 359 381T368 369T379 351T388 325T392 292Q392 230 343 187T222 143Q172 143 123 171Q112 153 112 133Q112 98 138 81Q147 75 155 75T227 73Q311 72 335 67Q396 58 431 26Q470 -13 470 -72Q470 -139 392 -175Q332 -206 250 -206Q167 -206 107 -175Q29 -140 29 -75Q29 -39 50 -15T92 18L103 24Q67 55 67 108Q67 155 96 193Q52 237 52 292Q52 355 102 398T223 442Q274 442 318 416L329 409ZM299 343Q294 371 273 387T221 404Q192 404 171 388T145 343Q142 326 142 292Q142 248 149 227T179 192Q196 182 222 182Q244 182 260 189T283 207T294 227T299 242Q302 258 302 292T299 343ZM403 -75Q403 -50 389 -34T348 -11T299 -2T245 0H218Q151 0 138 -6Q118 -15 107 -34T95 -74Q95 -84 101 -97T122 -127T170 -155T250 -167Q319 -167 361 -139T403 -75Z" transform="translate(778,0)"></path></g><g data-mml-node="mo" transform="translate(3484.7,0)"><path data-c="2061" d=""></path></g><g data-mml-node="mi" transform="translate(3651.3,0)"><path data-c="1D441" d="M234 637Q231 637 226 637Q201 637 196 638T191 649Q191 676 202 682Q204 683 299 683Q376 683 387 683T401 677Q612 181 616 168L670 381Q723 592 723 606Q723 633 659 637Q635 637 635 648Q635 650 637 660Q641 676 643 679T653 683Q656 683 684 682T767 680Q817 680 843 681T873 682Q888 682 888 672Q888 650 880 642Q878 637 858 637Q787 633 769 597L620 7Q618 0 599 0Q585 0 582 2Q579 5 453 305L326 604L261 344Q196 88 196 79Q201 46 268 46H278Q284 41 284 38T282 19Q278 6 272 0H259Q228 2 151 2Q123 2 100 2T63 2T46 1Q31 1 31 10Q31 14 34 26T39 40Q41 46 62 46Q130 49 150 85Q154 91 221 362L289 634Q287 635 234 637Z"></path></g><g data-mml-node="mo" transform="translate(4539.3,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g></g></g></svg></mjx-container></p></li></ul></section><section class="chapter"><h5 id="8-2-2-std-nth-element" data-toc="8-2-2-std-nth-element">8.2.2 std::nth_element</h5><p id="z7hbb6_655"><span id="z7hbb6_663"><font style="color:#8a2be2">Syntax:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <algorithm>">
#include <algorithm>
template <class RandomAccessIterator>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last);
// Optional: You can provide a custom comparison function
template <class RandomAccessIterator, class Compare>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last, Compare comp);
</div><p id="z7hbb6_657"><span id="z7hbb6_664"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="std::vector<int> numbers = {5, 2, 8, 1, 9, 3};">
std::vector<int> numbers = {5, 2, 8, 1, 9, 3};
std::nth_element(numbers.begin(), numbers.begin() + 2, numbers.end());
// Output: 2 1 3 8 9 5 (The element at index 2 is now '3',
// which is the 3rd smallest, but the rest are not sorted)
</div><p id="z7hbb6_659"><span id="z7hbb6_665"><font style="color:#8a2be2">Parameters:</font></span></p><ol class="list _decimal" id="z7hbb6_660" type="1"><li class="list__item" id="z7hbb6_666"><p id="z7hbb6_670"><span id="z7hbb6_671"><font style="color:#ff00ff">first:</font></span> Iterator to the beginning of the range.</p></li><li class="list__item" id="z7hbb6_667"><p id="z7hbb6_672"><span id="z7hbb6_673"><font style="color:#ff00ff">nth:</font></span> Iterator pointing to the position you want the nth element to be placed in.</p></li><li class="list__item" id="z7hbb6_668"><p id="z7hbb6_674"><span id="z7hbb6_675"><font style="color:#ff00ff">last:</font></span> Iterator to one past the end of the range.</p></li><li class="list__item" id="z7hbb6_669"><p id="z7hbb6_676"><span id="z7hbb6_677"><font style="color:#ff00ff">comp (optional):</font></span> A binary comparison function, similar to std::sort.</p></li></ol><p id="z7hbb6_661"><span id="z7hbb6_678"><font style="color:#8a2be2">Important notes:</font></span></p><ul class="list _bullet" id="z7hbb6_662"><li class="list__item" id="z7hbb6_679"><p id="z7hbb6_682">With this, you can efficiently find the median of a dataset without fully sorting it, or determine the <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.025ex;" xmlns="http://www.w3.org/2000/svg" width="2.878ex" height="1.956ex" role="img" focusable="false" viewBox="0 -853.7 1272.2 864.7"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="msup"><g data-mml-node="mi"><path data-c="1D458" d="M121 647Q121 657 125 670T137 683Q138 683 209 688T282 694Q294 694 294 686Q294 679 244 477Q194 279 194 272Q213 282 223 291Q247 309 292 354T362 415Q402 442 438 442Q468 442 485 423T503 369Q503 344 496 327T477 302T456 291T438 288Q418 288 406 299T394 328Q394 353 410 369T442 390L458 393Q446 405 434 405H430Q398 402 367 380T294 316T228 255Q230 254 243 252T267 246T293 238T320 224T342 206T359 180T365 147Q365 130 360 106T354 66Q354 26 381 26Q429 26 459 145Q461 153 479 153H483Q499 153 499 144Q499 139 496 130Q455 -11 378 -11Q333 -11 305 15T277 90Q277 108 280 121T283 145Q283 167 269 183T234 206T200 217T182 220H180Q168 178 159 139T145 81T136 44T129 20T122 7T111 -2Q98 -11 83 -11Q66 -11 57 -1T48 16Q48 26 85 176T158 471L195 616Q196 629 188 632T149 637H144Q134 637 131 637T124 640T121 647Z"></path></g><g data-mml-node="TeXAtom" transform="translate(554,363) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mtext"><path data-c="74" d="M27 422Q80 426 109 478T141 600V615H181V431H316V385H181V241Q182 116 182 100T189 68Q203 29 238 29Q282 29 292 100Q293 108 293 146V181H333V146V134Q333 57 291 17Q264 -10 221 -10Q187 -10 162 2T124 33T105 68T98 100Q97 107 97 248V385H18V422H27Z"></path><path data-c="68" d="M41 46H55Q94 46 102 60V68Q102 77 102 91T102 124T102 167T103 217T103 272T103 329Q103 366 103 407T103 482T102 542T102 586T102 603Q99 622 88 628T43 637H25V660Q25 683 27 683L37 684Q47 685 66 686T103 688Q120 689 140 690T170 693T181 694H184V367Q244 442 328 442Q451 442 463 329Q464 322 464 190V104Q464 66 466 59T477 49Q498 46 526 46H542V0H534L510 1Q487 2 460 2T422 3Q319 3 310 0H302V46H318Q379 46 379 62Q380 64 380 200Q379 335 378 343Q372 371 358 385T334 402T308 404Q263 404 229 370Q202 343 195 315T187 232V168V108Q187 78 188 68T191 55T200 49Q221 46 249 46H265V0H257L234 1Q210 2 183 2T145 3Q42 3 33 0H25V46H41Z" transform="translate(389,0)"></path></g></g></g></g></g></svg></mjx-container> smallest or largest element.</p></li><li class="list__item" id="z7hbb6_680"><p id="z7hbb6_684">It sorts so <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.025ex;" xmlns="http://www.w3.org/2000/svg" width="3.057ex" height="1.956ex" role="img" focusable="false" viewBox="0 -853.7 1351.2 864.7"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="msup"><g data-mml-node="mi"><path data-c="1D45B" d="M21 287Q22 293 24 303T36 341T56 388T89 425T135 442Q171 442 195 424T225 390T231 369Q231 367 232 367L243 378Q304 442 382 442Q436 442 469 415T503 336T465 179T427 52Q427 26 444 26Q450 26 453 27Q482 32 505 65T540 145Q542 153 560 153Q580 153 580 145Q580 144 576 130Q568 101 554 73T508 17T439 -10Q392 -10 371 17T350 73Q350 92 386 193T423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 180T152 343Q153 348 153 366Q153 405 129 405Q91 405 66 305Q60 285 60 284Q58 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="TeXAtom" transform="translate(633,363) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mtext"><path data-c="74" d="M27 422Q80 426 109 478T141 600V615H181V431H316V385H181V241Q182 116 182 100T189 68Q203 29 238 29Q282 29 292 100Q293 108 293 146V181H333V146V134Q333 57 291 17Q264 -10 221 -10Q187 -10 162 2T124 33T105 68T98 100Q97 107 97 248V385H18V422H27Z"></path><path data-c="68" d="M41 46H55Q94 46 102 60V68Q102 77 102 91T102 124T102 167T103 217T103 272T103 329Q103 366 103 407T103 482T102 542T102 586T102 603Q99 622 88 628T43 637H25V660Q25 683 27 683L37 684Q47 685 66 686T103 688Q120 689 140 690T170 693T181 694H184V367Q244 442 328 442Q451 442 463 329Q464 322 464 190V104Q464 66 466 59T477 49Q498 46 526 46H542V0H534L510 1Q487 2 460 2T422 3Q319 3 310 0H302V46H318Q379 46 379 62Q380 64 380 200Q379 335 378 343Q372 371 358 385T334 402T308 404Q263 404 229 370Q202 343 195 315T187 232V168V108Q187 78 188 68T191 55T200 49Q221 46 249 46H265V0H257L234 1Q210 2 183 2T145 3Q42 3 33 0H25V46H41Z" transform="translate(389,0)"></path></g></g></g></g></g></svg></mjx-container> element is in correct position, and all elements smaller to left, larger to right, but the elements before the <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.025ex;" xmlns="http://www.w3.org/2000/svg" width="3.057ex" height="1.956ex" role="img" focusable="false" viewBox="0 -853.7 1351.2 864.7"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="msup"><g data-mml-node="mi"><path data-c="1D45B" d="M21 287Q22 293 24 303T36 341T56 388T89 425T135 442Q171 442 195 424T225 390T231 369Q231 367 232 367L243 378Q304 442 382 442Q436 442 469 415T503 336T465 179T427 52Q427 26 444 26Q450 26 453 27Q482 32 505 65T540 145Q542 153 560 153Q580 153 580 145Q580 144 576 130Q568 101 554 73T508 17T439 -10Q392 -10 371 17T350 73Q350 92 386 193T423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 180T152 343Q153 348 153 366Q153 405 129 405Q91 405 66 305Q60 285 60 284Q58 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="TeXAtom" transform="translate(633,363) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mtext"><path data-c="74" d="M27 422Q80 426 109 478T141 600V615H181V431H316V385H181V241Q182 116 182 100T189 68Q203 29 238 29Q282 29 292 100Q293 108 293 146V181H333V146V134Q333 57 291 17Q264 -10 221 -10Q187 -10 162 2T124 33T105 68T98 100Q97 107 97 248V385H18V422H27Z"></path><path data-c="68" d="M41 46H55Q94 46 102 60V68Q102 77 102 91T102 124T102 167T103 217T103 272T103 329Q103 366 103 407T103 482T102 542T102 586T102 603Q99 622 88 628T43 637H25V660Q25 683 27 683L37 684Q47 685 66 686T103 688Q120 689 140 690T170 693T181 694H184V367Q244 442 328 442Q451 442 463 329Q464 322 464 190V104Q464 66 466 59T477 49Q498 46 526 46H542V0H534L510 1Q487 2 460 2T422 3Q319 3 310 0H302V46H318Q379 46 379 62Q380 64 380 200Q379 335 378 343Q372 371 358 385T334 402T308 404Q263 404 229 370Q202 343 195 315T187 232V168V108Q187 78 188 68T191 55T200 49Q221 46 249 46H265V0H257L234 1Q210 2 183 2T145 3Q42 3 33 0H25V46H41Z" transform="translate(389,0)"></path></g></g></g></g></g></svg></mjx-container> element are not guaranteed to be sorted among themselves, and neither are the elements after it.</p></li><li class="list__item" id="z7hbb6_681"><p id="z7hbb6_687"><span id="z7hbb6_688"><font style="color:#ff00ff">Average case:</font></span> <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="5.495ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 2429 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mi"><path data-c="1D442" d="M740 435Q740 320 676 213T511 42T304 -22Q207 -22 138 35T51 201Q50 209 50 244Q50 346 98 438T227 601Q351 704 476 704Q514 704 524 703Q621 689 680 617T740 435ZM637 476Q637 565 591 615T476 665Q396 665 322 605Q242 542 200 428T157 216Q157 126 200 73T314 19Q404 19 485 98T608 313Q637 408 637 476Z"></path></g><g data-mml-node="mo" transform="translate(763,0)"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mi" transform="translate(1152,0)"><path data-c="1D441" d="M234 637Q231 637 226 637Q201 637 196 638T191 649Q191 676 202 682Q204 683 299 683Q376 683 387 683T401 677Q612 181 616 168L670 381Q723 592 723 606Q723 633 659 637Q635 637 635 648Q635 650 637 660Q641 676 643 679T653 683Q656 683 684 682T767 680Q817 680 843 681T873 682Q888 682 888 672Q888 650 880 642Q878 637 858 637Q787 633 769 597L620 7Q618 0 599 0Q585 0 582 2Q579 5 453 305L326 604L261 344Q196 88 196 79Q201 46 268 46H278Q284 41 284 38T282 19Q278 6 272 0H259Q228 2 151 2Q123 2 100 2T63 2T46 1Q31 1 31 10Q31 14 34 26T39 40Q41 46 62 46Q130 49 150 85Q154 91 221 362L289 634Q287 635 234 637Z"></path></g><g data-mml-node="mo" transform="translate(2040,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g></g></g></svg></mjx-container></p></li></ul></section><section class="chapter"><h5 id="8-2-3-std-stable-partition" data-toc="8-2-3-std-stable-partition">8.2.3 std::stable_partition</h5><p id="z7hbb6_690"><span id="z7hbb6_696"><font style="color:#8a2be2">Syntax:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <algorithm> // Required header">
#include <algorithm> // Required header
template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator stable_partition (BidirectionalIterator first,
BidirectionalIterator last,
UnaryPredicate pred);
</div><p id="z7hbb6_692"><span id="z7hbb6_697"><font style="color:#8a2be2">Parameters:</font></span></p><ol class="list _decimal" id="z7hbb6_693" type="1"><li class="list__item" id="z7hbb6_698"><p id="z7hbb6_704"><span id="z7hbb6_705"><font style="color:#ff00ff">BidirectionalIterator:</font></span> A template parameter indicating the type of iterators used. These iterators must support bidirectional movement (like those from std::list, std::vector, std::deque).</p></li><li class="list__item" id="z7hbb6_699"><p id="z7hbb6_706"><span id="z7hbb6_707"><font style="color:#ff00ff">first (BidirectionalIterator):</font></span> An iterator to the beginning of the range you want to partition.</p></li><li class="list__item" id="z7hbb6_700"><p id="z7hbb6_708"><span id="z7hbb6_709"><font style="color:#ff00ff">last (BidirectionalIterator):</font></span> An iterator to one past the end of the range to be partitioned.</p></li><li class="list__item" id="z7hbb6_701"><p id="z7hbb6_710"><span id="z7hbb6_711"><font style="color:#ff00ff">UnaryPredicate:</font></span> A template parameter representing the type of the predicate function.</p></li><li class="list__item" id="z7hbb6_702"><p id="z7hbb6_712"><span id="z7hbb6_713"><font style="color:#ff00ff">pred (UnaryPredicate):</font></span> A function that takes a single argument (an element from the range) and returns a bool:</p></li><li class="list__item" id="z7hbb6_703"><ul class="list _bullet" id="z7hbb6_714"><li class="list__item" id="z7hbb6_715"><p id="z7hbb6_717">true: The element satisfies the partitioning criterion.</p></li><li class="list__item" id="z7hbb6_716"><p id="z7hbb6_718">false: The element does not satisfy the criterion.</p></li></ul></li></ol><p id="z7hbb6_694"><span id="z7hbb6_719"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
// A simple struct to represent a course (you can customize this)
struct Course {
std::string name;
};
int main() {
// Sample course data
std::vector<Course> courses = {
{"CS101"},
{"MATH101"},
{"CS202"},
{"PHYS101"},
{"CS301"}
};
std::string dep = "CS";
// Lambda function to check if a course belongs to the "CS" department
auto isDep = [dep](const Course& course) {
return course.name.size() >= dep.size() &&
course.name.substr(0, dep.size()) == dep;
};
// Partition the courses vector, keeping "CS" courses at the beginning
auto iter = std::stable_partition(courses.begin(), courses.end(), isDep);
// Remove non-"CS" courses
courses.erase(iter, courses.end());
// Output the remaining "CS" courses
std::cout << "CS Courses:\n";
for (const Course& course : courses) {
std::cout << course.name << std::endl;
}
return 0;
}
</div></section><section class="chapter"><h5 id="8-2-4-std-copy-if" data-toc="8-2-4-std-copy-if">8.2.4 std::copy_if</h5><p id="z7hbb6_720"><span id="z7hbb6_725"><font style="color:#8a2be2">Syntax:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <algorithm> // Required header">
#include <algorithm> // Required header
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
</div><ol class="list _decimal" id="z7hbb6_722" type="1"><li class="list__item" id="z7hbb6_726"><p id="z7hbb6_734"><span id="z7hbb6_735"><font style="color:#ff00ff">InputIterator:</font></span> Type of iterator used for the input range.</p></li><li class="list__item" id="z7hbb6_727"><p id="z7hbb6_736"><span id="z7hbb6_737"><font style="color:#ff00ff">OutputIterator:</font></span> Type of iterator used for the output range (where copied elements go).</p></li><li class="list__item" id="z7hbb6_728"><p id="z7hbb6_738"><span id="z7hbb6_739"><font style="color:#ff00ff">first (InputIterator):</font></span> An iterator to the beginning of the input range.</p></li><li class="list__item" id="z7hbb6_729"><p id="z7hbb6_740"><span id="z7hbb6_741"><font style="color:#ff00ff">last (InputIterator):</font></span> An iterator to one past the end of the input range.</p></li><li class="list__item" id="z7hbb6_730"><p id="z7hbb6_742"><span id="z7hbb6_743"><font style="color:#ff00ff">result (OutputIterator):</font></span> An iterator to the beginning of the output range.</p></li><li class="list__item" id="z7hbb6_731"><p id="z7hbb6_744"><span id="z7hbb6_745"><font style="color:#ff00ff">UnaryPredicate:</font></span> Type of the predicate function.</p></li><li class="list__item" id="z7hbb6_732"><p id="z7hbb6_746"><span id="z7hbb6_747"><font style="color:#ff00ff">pred (UnaryPredicate):</font></span> A function that takes a single argument (an element from the input range) and returns:</p></li><li class="list__item" id="z7hbb6_733"><ul class="list _bullet" id="z7hbb6_748"><li class="list__item" id="z7hbb6_749"><p id="z7hbb6_751">true: Copy the element to the output range.</p></li><li class="list__item" id="z7hbb6_750"><p id="z7hbb6_752">false: Skip the element.</p></li></ul></li></ol><p id="z7hbb6_723"><span id="z7hbb6_753"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Course {
std::string name;
};
int main() {
std::vector<Course> csCourses = {
{"CS101"},
{"MATH101"},
{"CS202"},
{"PHYS101"},
{"CS301"}
};
std::vector<Course> filteredCourses;
std::string dep = "CS";
auto isDep = [dep](const Course& course) {
return course.name.size() >= dep.size() &&
course.name.substr(0, dep.size()) == dep;
};
// Copy matching courses to 'filteredCourses'
// Use back_inserter to add more space!
std::copy_if(csCourses.begin(), csCourses.end(),
std::back_inserter(filteredCourses), isDep);
std::cout << "Filtered CS Courses:\n";
for (const Course& course : filteredCourses) {
std::cout << course.name << std::endl;
}
return 0;
}
</div></section><section class="chapter"><h5 id="8-2-5-std-remove-if" data-toc="8-2-5-std-remove-if">8.2.5 std::remove_if</h5><p id="z7hbb6_754"><span id="z7hbb6_757"><font style="color:#8a2be2">Syntax:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <algorithm> // Required header">
#include <algorithm> // Required header
template <class ForwardIterator, class UnaryPredicate>
ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
UnaryPredicate pred);
</div><ol class="list _decimal" id="z7hbb6_756" type="1"><li class="list__item" id="z7hbb6_758"><p id="z7hbb6_764"><span id="z7hbb6_765"><font style="color:#ff00ff">ForwardIterator:</font></span> Type of iterator used for the range. Must support forward movement.</p></li><li class="list__item" id="z7hbb6_759"><p id="z7hbb6_766"><span id="z7hbb6_767"><font style="color:#ff00ff">first (ForwardIterator):</font></span> An iterator to the beginning of the range.</p></li><li class="list__item" id="z7hbb6_760"><p id="z7hbb6_768"><span id="z7hbb6_769"><font style="color:#ff00ff">last (ForwardIterator):</font></span> An iterator to one past the end of the range.</p></li><li class="list__item" id="z7hbb6_761"><p id="z7hbb6_770"><span id="z7hbb6_771"><font style="color:#ff00ff">UnaryPredicate:</font></span> Type of the predicate function.</p></li><li class="list__item" id="z7hbb6_762"><p id="z7hbb6_772"><span id="z7hbb6_773"><font style="color:#ff00ff">pred (UnaryPredicate):</font></span> A function that takes a single argument (an element from the range) and returns:</p></li><li class="list__item" id="z7hbb6_763"><ul class="list _bullet" id="z7hbb6_774"><li class="list__item" id="z7hbb6_775"><p id="z7hbb6_777">true: The element should be "removed."</p></li><li class="list__item" id="z7hbb6_776"><p id="z7hbb6_778">false: The element should be kept.</p></li></ul></li></ol></section></section></section></section><section class="chapter"><h2 id="object" data-toc="object">Ⅲ Object-Oriented Programming</h2><section class="chapter"><h3 id="9-classes-and-consts" data-toc="9-classes-and-consts">9 Classes and Consts</h3><section class="chapter"><h4 id="9-1-classes" data-toc="9-1-classes">9.1 Classes</h4><p id="z7hbb6_787"><span id="z7hbb6_798"><font style="color:#8a2be2">Definitions:</font></span></p><ul class="list _bullet" id="z7hbb6_788"><li class="list__item" id="z7hbb6_799"><p id="z7hbb6_807"><span id="z7hbb6_808"><font style="color:#ff8c00">Class:</font></span> a template for a new type of objects, defines how objects of a particular type behave.</p></li><li class="list__item" id="z7hbb6_800"><p id="z7hbb6_809"><span id="z7hbb6_810"><font style="color:#ff8c00">Object:</font></span> Entity that combines state and behavior, instance of a class.</p></li><li class="list__item" id="z7hbb6_801"><p id="z7hbb6_811"><span id="z7hbb6_812"><font style="color:#ff8c00">Member variables (instance variables, fields):</font></span> Define state inside each object.</p></li><li class="list__item" id="z7hbb6_802"><p id="z7hbb6_813"><span id="z7hbb6_814"><font style="color:#ff8c00">Member functions (methods):</font></span> Define behavior inside each object.</p></li><li class="list__item" id="z7hbb6_803"><p id="z7hbb6_815"><span id="z7hbb6_816"><font style="color:#ff8c00">Constructor:</font></span> Initializes the state of newly created objects.</p></li><li class="list__item" id="z7hbb6_804"><p id="z7hbb6_817"><span id="z7hbb6_819"><font style="color:#ff8c00">Destructor:</font></span> Called when the object is deleted by the program.</p><ul class="list _bullet" id="z7hbb6_818"><li class="list__item" id="z7hbb6_820"><p id="z7hbb6_822">Delete any pointers stored as private members.</p></li><li class="list__item" id="z7hbb6_821"><p id="z7hbb6_823">delete[] any arrays stored as private members.</p></li></ul></li><li class="list__item" id="z7hbb6_805"><p id="z7hbb6_824"><span id="z7hbb6_825"><font style="color:#ff8c00">Client code:</font></span> Code that uses the objects defind.</p></li><li class="list__item" id="z7hbb6_806"><p id="z7hbb6_826"><span id="z7hbb6_827"><font style="color:#ff8c00">Encapsulation:</font></span> Hiding implementation details from the client code.</p></li></ul><p id="z7hbb6_789">C++ separates classes into two kinds of files:</p><ul class="list _bullet" id="z7hbb6_790"><li class="list__item" id="z7hbb6_828"><p id="z7hbb6_830"><span id="z7hbb6_831"><font style="color:#ff00ff">Header File</font></span> (<span id="z7hbb6_832"><font style="color:#ff4500">.h</font></span>, .hh, .hpp): Containing the interface (declarations).</p></li><li class="list__item" id="z7hbb6_829"><p id="z7hbb6_833"><span id="z7hbb6_834"><font style="color:#ff00ff">Source File</font></span> (<span id="z7hbb6_835"><font style="color:#ff4500">.cpp</font></span>, .cc, .cxx, .c++, .C): Containing definitions (method bodies).</p></li></ul><p id="z7hbb6_791">Classes have <span id="z7hbb6_836"><font style="color:#ff4500">three</font></span> main parts:</p><ul class="list _bullet" id="z7hbb6_792"><li class="list__item" id="z7hbb6_837"><p id="z7hbb6_840"><span id="z7hbb6_841"><font style="color:#ff00ff">Constructor and destructor</font></span></p></li><li class="list__item" id="z7hbb6_838"><p id="z7hbb6_842"><span id="z7hbb6_843"><font style="color:#ff00ff">Member variables</font></span></p></li><li class="list__item" id="z7hbb6_839"><p id="z7hbb6_844"><span id="z7hbb6_845"><font style="color:#ff00ff">Member functions</font></span></p></li></ul><p id="z7hbb6_793"><span id="z7hbb6_846"><font style="color:#8a2be2">Example (header file):</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="// Protection in case multiple .cpp files include this header, so">
// Protection in case multiple .cpp files include this header, so
// that its contents won't get declared twice.
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass {
public:
MyClass(); // Constructor
~MyClass(); // Destructor
void myMethod(); // Member function (behavior inside each function)
int getMyVariable();
private:
int myVariable; // Member variable (data inside each object)
}; // Semicolons!
#endif // MYCLASS_H
</div><p id="z7hbb6_795"><span id="z7hbb6_847"><font style="color:#8a2be2">Example (source file):</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include "MyClass.h"">
#include "MyClass.h"
MyClass::MyClass() {
myVariable = 0; // Initialize member variable
}
void MyClass::myMethod() {
myVariable++;
}
MyClass::~MyClass() {
// Simple destructor implementation
}
int MyClass::getMyVariable() {
return myVariable;
}
</div><aside class="prompt" data-type="note" data-title="" id="z7hbb6_797"><p id="z7hbb6_848">Why so many extensions?</p><p id="z7hbb6_849">Depend on the compilers!</p><ul class="list _bullet" id="z7hbb6_850"><li class="list__item" id="z7hbb6_851"><p id="z7hbb6_854">Historically, used .C</p></li><li class="list__item" id="z7hbb6_852"><p id="z7hbb6_855">Now, Unix most uses <span id="z7hbb6_856"><font style="color:#ff4500">.cc</font></span>, and outside Unix mostly uses <span id="z7hbb6_857"><font style="color:#ff4500">.cpp</font></span></p></li><li class="list__item" id="z7hbb6_853"><p id="z7hbb6_858">.h is technically for C programs, so if mixing C and C++ code, use .hh instead</p></li></ul></aside></section><section class="chapter"><h4 id="9-2-consts" data-toc="9-2-consts">9.2 Consts</h4><p id="z7hbb6_859"><span id="z7hbb6_868"><font style="color:#ff8c00">Consts:</font></span> A qualifier for objects that declares they cannot be modified.</p><p id="z7hbb6_860">Consts help us find bugs, and allow us to reason about whether a variable will be changed.</p><p id="z7hbb6_861">Within a function that takes a const parameter, you cannot call non-const member functions (if the parameter is an object) or modify the value (if it's a fundamental type or a pointer to const data) of that parameter.</p><p id="z7hbb6_862"><span id="z7hbb6_869"><font style="color:#8a2be2">Example for value:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="int plus(const int& x) {">
int plus(const int& x) {
return x + 1; // Error: x is const
}
int plus(const int x) {
return x + 1; // OK: x is a copy
}
</div><p id="z7hbb6_864"><span id="z7hbb6_870"><font style="color:#8a2be2">Example for member functions:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="struct Planet {">
struct Planet {
int countPopulation() const;
void deathStar();
};
int Planet::countPopulation() const {
return 42;
}
void Planet::deathStar() {
std::cout << "BOOM" << std::endl;
}
void evil(const Planet &p) {
// OK: countPopulation is const
std::cout << p.countPopulation() << std::endl;
// ERROR: deathStar isn't const
p.deathStar();
}
</div><section class="chapter"><h5 id="9-2-1-const-pointers" data-toc="9-2-1-const-pointers">9.2.1 Const Pointers</h5><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="// constant pointer to a non-constant int">
// constant pointer to a non-constant int
// (*p)++; OK!
// p++; NOT allowed!
int * const p;
// non-constant pointer to a constant
int const int* p;
int const* p;
// constant pointer to a constant
int const int* const p;
int const* const p;
</div><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_872"><p id="z7hbb6_873">When in doubt, read from right to left!</p><p id="z7hbb6_874">You can't declare a non-const reference to a const variable!</p></aside></section><section class="chapter"><h5 id="9-2-2-const-iterators" data-toc="9-2-2-const-iterators">9.2.2 Const Iterators</h5><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="const vector<int>::iterator itr = v.begin();">
const vector<int>::iterator itr = v.begin();
*itr = 5; // OK! changing what itr points to
++itr; // ERROR! can’t modify itr
vector<int>::const_iterator itr = v.begin();
*itr = 5; //ERROR! can’t change value of itr
++itr; //OK! changing v
int value = *itr; //OK! reading from itr
</div></section></section></section><section class="chapter"><h3 id="10-operators" data-toc="10-operators">10 Operators</h3><section class="chapter"><h4 id="10-1-basic-operators" data-toc="10-1-basic-operators">10.1 Basic Operators</h4><p id="z7hbb6_880">There are 40 (+4) operators you can overload!</p><figure id="z7hbb6_881"><img alt="Operators" src="Computer-Science-Study-Notes/c8-1.png" title="Operators" width="1899" height="1141"></figure><p id="z7hbb6_882"><span id="z7hbb6_886"><font style="color:#8a2be2">Examples for default operators behaviors:</font></span></p><div class="code-comparer" id="z7hbb6_883" data-comparing="horizontally"><div class="code-block" data-lang="cpp" data-title="Before">
std::vector<std::string> v{"Hello", "World"};
std::cout << v[0];
v[1] += "!";
</div><div class="code-block" data-lang="cpp" data-title="After">
std::vector<std::string> v{"Hello", "World"};
std::cout.operator << (v.operator[](0).c_str());
v.operator[](1).operator += ("!");
</div></div><p id="z7hbb6_884">In STL,</p><div class="code-block" data-lang="cpp">
ostream& operator<<(ostream& s, const string& val) {
...
}
string& vector<string>::operator[](size_t index) const {
...
}
</div></section><section class="chapter"><h4 id="10-2-operator-overloading" data-toc="10-2-operator-overloading">10.2 Operator Overloading</h4><p id="z7hbb6_889"><span id="z7hbb6_898"><font style="color:#8a2be2">General rule of Thumb:</font></span> (Member & Non-Member)</p><ol class="list _decimal" id="z7hbb6_890" type="1"><li class="list__item" id="z7hbb6_899"><p>Some operators must be implemented as members (e.g., [], (), ->, =) due to C++ semantics.</p></li><li class="list__item" id="z7hbb6_900"><p>Some must be implemented as non-members (eg. <<, if you are writing class for rhs, not lhs).</p></li><li class="list__item" id="z7hbb6_901"><p>If unary operator (eg. ++), implement as member.</p></li><li class="list__item" id="z7hbb6_902"><p>If binary operator and treats both operands equally (eg. both unchanged) implement as non-member (maybe friend). Examples: +, < .</p></li><li class="list__item" id="z7hbb6_903"><p>If binary operator and not both equally (changes lhs), implement as member (allows easy access to lhs private members). Examples: +=</p></li></ol><aside class="prompt" data-type="tip" data-title="" id="z7hbb6_891"><ol class="list _decimal" id="z7hbb6_904" type="1"><li class="list__item" id="z7hbb6_905"><p>Always think about const-ness of parameters.</p></li><li class="list__item" id="z7hbb6_906"><p>Return reference to support chaining << calls.</p></li><li class="list__item" id="z7hbb6_907"><p>Here we are overloading << so our class works as the rhs... but we can't change the class of lhs (stream library).</p></li></ol></aside><p id="z7hbb6_892"><span id="z7hbb6_908"><font style="color:#cd5c5c">Examples</font></span></p><p id="z7hbb6_893"><span id="z7hbb6_909"><font style="color:#ff00ff">Member Function:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
class MyClass {
private:
int data[10];
public:
// Subscript operator ([])
int& operator[](int index) {
return data[index];
}
// Function call operator ()
int operator()(int a, int b) {
return data[a] + data[b];
}
// Assignment operator (=)
MyClass& operator=(const MyClass& other) {
if (this != &other) { // Avoid self-assignment
for (int i = 0; i < 10; ++i) {
data[i] = other.data[i];
}
}
return *this;
}
};
int main() {
MyClass obj;
obj[2] = 5; // Using the subscript operator
obj[3] = 10; // Using the subscript operator
int sum = obj(2, 3); // Using the function call operator
std::cout << "Sum: " << sum << std::endl;
MyClass obj2;
obj2 = obj; // Using the assignment operator
return 0;
}
</div><p id="z7hbb6_895"><span id="z7hbb6_910"><font style="color:#ff00ff">Non-Member Function:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
class Point {
private:
int x, y;
public:
Point(int xVal, int yVal) : x(xVal), y(yVal) {}
// Friend declaration for the output stream operator
friend std::ostream& operator<<(std::ostream& out, const Point& p);
};
// Non-member output stream operator (<<)
std::ostream& operator<<(std::ostream& out, const Point& p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
};
int main() {
Point p(5, 10);
std::cout << "Point coordinates: " << p << std::endl; // Using the overloaded <<
return 0;
}
</div><aside class="prompt" data-type="note" data-title="" id="z7hbb6_897"><p id="z7hbb6_911">Declare non-member functions as friends of a class to give them access to private members.</p></aside></section><section class="chapter"><h4 id="10-3-principle-of-least-astonishment-pola" data-toc="10-3-principle-of-least-astonishment-pola">10.3 Principle of Least Astonishment (POLA)</h4><p id="z7hbb6_912"><span id="z7hbb6_914"><font style="color:#8a2be2">From the C++ Core Guidelines (section C ):</font></span></p><ul class="list _bullet" id="z7hbb6_913"><li class="list__item" id="z7hbb6_915"><p id="z7hbb6_919">Design operators primarily to mimic conventional usage.</p></li><li class="list__item" id="z7hbb6_916"><p id="z7hbb6_920">Use nonmember functions for symmetric operators.</p></li><li class="list__item" id="z7hbb6_917"><p id="z7hbb6_921">Use nonmember functions for symmetric operators.</p><ul class="list _bullet" id="z7hbb6_922"><li class="list__item" id="z7hbb6_923"><p id="z7hbb6_928">Compound operators return reference to *this</p></li><li class="list__item" id="z7hbb6_924"><p id="z7hbb6_929">Arithmetic operators return copies</p></li><li class="list__item" id="z7hbb6_925"><p id="z7hbb6_930">In/decrement prefix vs. postfix rules</p></li><li class="list__item" id="z7hbb6_926"><p id="z7hbb6_931">Indexing requires const and non-const versions</p></li><li class="list__item" id="z7hbb6_927"><p id="z7hbb6_932">Look at the C++ reference for common patterns!</p></li></ul></li><li class="list__item" id="z7hbb6_918"><p>Always provide all out of a set of related operators.</p></li></ul></section><section class="chapter"><h4 id="10-4-interesting-operators" data-toc="10-4-interesting-operators">10.4 Interesting Operators</h4><p id="z7hbb6_933"><span id="z7hbb6_937"><font style="color:#8a2be2">Advanced Multithreading Support (C++ 20) :</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="awaiter operator co_await() const noexcept {">
awaiter operator co_await() const noexcept {
return awaiter{ *this };
}
</div><p id="z7hbb6_935"><span id="z7hbb6_938"><font style="color:#8a2be2">Spaceship operator (C++20):</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="std::strong_ordering operator<=> (const Time& rhs) {">
std::strong_ordering operator<=> (const Time& rhs) {
return hour <=> rhs.hour;
}
</div></section></section><section class="chapter"><h3 id="11-special-member-functions" data-toc="11-special-member-functions">11 Special Member Functions</h3><p id="z7hbb6_939"><span id="z7hbb6_950"><font style="color:#8a2be2">Six types of special member functions:</font></span></p><p id="z7hbb6_940">Every class has them by default.</p><p id="z7hbb6_941">These functions are generated only when they're called (and before any are explicitly defined by you):</p><ul class="list _bullet" id="z7hbb6_942"><li class="list__item" id="z7hbb6_951"><p id="z7hbb6_957"><span id="z7hbb6_958"><font style="color:#ff00ff">Default constructor:</font></span> Takes no parameters and creates a new object.</p></li><li class="list__item" id="z7hbb6_952"><p id="z7hbb6_959"><span id="z7hbb6_960"><font style="color:#ff00ff">Destructor:</font></span> Called when an object goes out of scope.</p></li><li class="list__item" id="z7hbb6_953"><p id="z7hbb6_961"><span id="z7hbb6_962"><font style="color:#ff00ff">Copy constructor:</font></span> Creates a <span id="z7hbb6_963"><u>new object</u></span> as a member-wise copy of another.</p></li><li class="list__item" id="z7hbb6_954"><p id="z7hbb6_964"><span id="z7hbb6_965"><font style="color:#ff00ff">Copy assignment operator:</font></span> Assigns an <span id="z7hbb6_966"><u>already existing object</u></span> to another.</p></li><li class="list__item" id="z7hbb6_955"><p id="z7hbb6_967">Move constructor</p></li><li class="list__item" id="z7hbb6_956"><p id="z7hbb6_968">Move assignment operator</p></li></ul><p id="z7hbb6_943"><span id="z7hbb6_969"><font style="color:#8a2be2">Example:</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="MyVector<int> function(MyVector<int> vec0) { // copy constructor">
MyVector<int> function(MyVector<int> vec0) { // copy constructor
MyVector<int> vec1; // default constructor
MyVector<int> vec2{3, 4, 5}; // initializer list constructor
MyVector<int> vec3(); // function declaration - C++’s most vexing parse
MyVector<int> vec4(vec2); // copy constructor
MyVector<int> vec5{}; // default constructor
MyVector<int> vec6{vec3 + vec4}; // move constructor
MyVector<int> vec7 = vec4; // copy constructor
vec7 = vec2; // copy assignment operator
return vec7; // move constructor
</div><aside class="prompt" data-type="note" data-title="" id="z7hbb6_945"><p id="z7hbb6_970">About the return value:</p><ol class="list _decimal" id="z7hbb6_971" type="1"><li class="list__item" id="z7hbb6_972"><p id="z7hbb6_974"><span id="z7hbb6_975"><font style="color:#ff00ff">Return Value Optimization (RVO):</font></span> The compiler is allowed to optimize away the copy/move entirely and construct vec7 directly in the location where the return value will be placed. This eliminates any copying or moving.</p></li><li class="list__item" id="z7hbb6_973"><p id="z7hbb6_976"><span id="z7hbb6_977"><font style="color:#ff00ff">Move Semantics:</font></span> If RVO is not applicable (e.g., due to complex control flow or compiler limitations ), the compiler will prefer to use the move constructor because vec7 is a local variable that is going out of scope. This means its resources can be "moved" to the return value efficiently, rather than copying them.</p></li></ol></aside><section class="chapter"><h4 id="11-1-copy-constructor-copy-assignment-operator" data-toc="11-1-copy-constructor-copy-assignment-operator">11.1 Copy Constructor & Copy Assignment Operator</h4><p id="z7hbb6_978">By default, the copy constructor will create copies of each member variable.</p><p id="z7hbb6_979"><span id="z7hbb6_987"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="/** Problem with the following code:">
/** Problem with the following code:
* When the vectors go out of scope, their destructor tries to free the array.
*/
IntVector operator+(const IntVector & vec, int elem) {
IntVector copy = vec; // default copy constructor, copy a pointer to the same array
copy += element;
return copy;
}
</div><figure id="z7hbb6_981"><img alt="Copy Constructor" src="Computer-Science-Study-Notes/c11-1.png" title="Copy Constructor" width="8192" height="4698"></figure><aside class="prompt" data-type="note" data-title="" id="z7hbb6_982"><p id="z7hbb6_988">When the vectors go out of scope, their destructor tries to free the array.</p></aside><p id="z7hbb6_983"><span id="z7hbb6_989"><font style="color:#8a2be2">Copy constructor:</font></span></p><ul class="list _bullet" id="z7hbb6_984"><li class="list__item" id="z7hbb6_990"><p id="z7hbb6_992">Use initializer list to copy members where assignment does the correct thing. e.g., int, other objects, etc.</p></li><li class="list__item" id="z7hbb6_991"><p id="z7hbb6_993">Deep copy all members where assignment does not work. e.g., pointers to heap memory.</p></li></ul><p id="z7hbb6_985"><span id="z7hbb6_994"><font style="color:#8a2be2">Copy assignment operator:</font></span></p><ul class="list _bullet" id="z7hbb6_986"><li class="list__item" id="z7hbb6_995"><p id="z7hbb6_998">Clean up any resources in the existing object about to be overwritten.</p></li><li class="list__item" id="z7hbb6_996"><p id="z7hbb6_999">Copy members using initializer list when assignment works.</p></li><li class="list__item" id="z7hbb6_997"><p id="z7hbb6_1000">Deep copy members where assignment does not work.</p></li></ul></section><section class="chapter"><h4 id="11-2-delete-operations" data-toc="11-2-delete-operations">11.2 Delete Operations</h4><p id="z7hbb6_1001">Setting a special member function to delete removes its functionality.</p><p id="z7hbb6_1002">We can also keep the default copy constructor if we declare other constructors.</p><p id="z7hbb6_1003"><span id="z7hbb6_1005"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
class NonCopyable {
public:
NonCopyable() = default; // Default constructor
NonCopyable(const NonCopyable&) = delete; // Delete copy constructor
NonCopyable& operator=(const NonCopyable&) = delete; // Delete copy assignment
NonCopyable(NonCopyable&&) = default; // Default move constructor
NonCopyable& operator=(NonCopyable&&) = default; // Default move assignment
void print() { std::cout << "NonCopyable object" << std::endl; }
};
int main() {
NonCopyable obj1;
obj1.print();
NonCopyable obj2 = std::move(obj1); // Move construction is allowed
obj2.print();
// NonCopyable obj3 = obj2; // Error: Copy construction is deleted
// obj1 = obj2; // Error: Copy assignment is deleted
return 0;
}
</div></section><section class="chapter"><h4 id="11-3-rule-of-zero-three" data-toc="11-3-rule-of-zero-three">11.3 Rule of Zero/Three</h4><p id="z7hbb6_1006"><span id="z7hbb6_1011"><font style="color:#8a2be2">Rule of Zero:</font></span> If the default operations work, don't define your own custom ones!</p><p id="z7hbb6_1007">When the default one generated by the compiler does not work, you need to write your own special member functions.</p><p id="z7hbb6_1008">Most common reason: ownership issues. A member is a handle on a resource outside of the class (e.g., pointers, mutexes, filestreams) .</p><p id="z7hbb6_1009"><span id="z7hbb6_1012"><font style="color:#8a2be2">Rule of Three:</font></span> If you explicitly define (or delete) a copy constructor, copy assignment, or destructor, you should define (or delete) all three.</p><aside class="prompt" data-type="note" data-title="" id="z7hbb6_1010"><p id="z7hbb6_1013">The fact that you defined one of these means one of your members has ownership issues that need to be resolved.</p></aside></section><section class="chapter"><h4 id="11-4-copy-elision-and-return-value-optimization-rvo" data-toc="11-4-copy-elision-and-return-value-optimization-rvo">11.4 Copy Elision and Return Value Optimization (RVO)</h4><p id="z7hbb6_1014"><span id="z7hbb6_1017"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="int main() {">
int main() {
StringVector words;
words = findAllWords(“words.txt”); // print words
}
StringVector findAllWords(const string& filename) {
StringVector words;
// read from filename using an ifstream
return words;
}
</div><figure id="z7hbb6_1016"><img alt="RVO" src="Computer-Science-Study-Notes/c11-2.png" title="RVO" width="2667" height="1500"></figure></section></section><section class="chapter"><h3 id="12-move-semantics" data-toc="12-move-semantics">12 Move Semantics</h3><section class="chapter"><h4 id="12-1-lvalues-rvalues" data-toc="12-1-lvalues-rvalues">12.1 lvalues & rvalues</h4><p id="z7hbb6_1020"><span id="z7hbb6_1028"><font style="color:#8a2be2">Definitions</font></span></p><ul class="list _bullet" id="z7hbb6_1021"><li class="list__item" id="z7hbb6_1029"><p id="z7hbb6_1031"><span id="z7hbb6_1032"><font style="color:#ff8c00">lvalue:</font></span> An l-value is an expression that has a name (identity).</p></li><li class="list__item" id="z7hbb6_1030"><p id="z7hbb6_1033"><span id="z7hbb6_1034"><font style="color:#ff8c00">rvalue:</font></span> An r-value is an expression that does not have a name (identity).</p></li></ul><div class="table-wrapper"><table class="left_header wide" id="z7hbb6_1022"><thead><tr class="ijRowHead" id="z7hbb6_1035"><th id="z7hbb6_1041"></th><th id="z7hbb6_1042"><p>l-value</p></th><th id="z7hbb6_1043"><p>r-value</p></th></tr></thead><tbody><tr id="z7hbb6_1036"><th id="z7hbb6_1044"><p>Find address using address-of operator (&var)</p></th><td id="z7hbb6_1045"><p>Yes</p></td><td id="z7hbb6_1046"><p>No</p></td></tr><tr id="z7hbb6_1037"><th id="z7hbb6_1047"><p>Intuitive Definition</p></th><td id="z7hbb6_1048"><p>Can appear either left or right of an assignment *</p></td><td id="z7hbb6_1049"><p>Can appear only on the right of an assignment *</p></td></tr><tr id="z7hbb6_1038"><th id="z7hbb6_1050"><p>Lifetime</p></th><td id="z7hbb6_1051"><p>Decided by scope</p></td><td id="z7hbb6_1052"><p>Ends on the very next line (unless you purposely extend it!)</p></td></tr><tr id="z7hbb6_1039"><th id="z7hbb6_1053" rowspan="2"><p>Value References</p></th><td id="z7hbb6_1054"><p id="z7hbb6_1056">An <span id="z7hbb6_1058"><font style="color:#ff4500">l-value</font></span> reference can bind to an l-value.</p><div class="code-block" data-lang="cpp">
auto& ptr2 = (ptr += 3);
</div></td><td id="z7hbb6_1055"><p id="z7hbb6_1059">An <span id="z7hbb6_1061"><font style="color:#ff4500">r-value</font></span> reference can bind to an r-value.</p><div class="code-block" data-lang="cpp">
auto&& v4 = v1 + v2;
</div></td></tr><tr id="z7hbb6_1040"><th id="z7hbb6_1062" colspan="2"><p id="z7hbb6_1063">A <span id="z7hbb6_1065"><font style="color:#dda0dd">const</font></span> <span id="z7hbb6_1066"><font style="color:#ff4500">l-value</font></span> reference can bind to either l or r-value.</p><div class="code-block" data-lang="cpp">
const auto& ptr2 = (ptr += 3);
const auto& v4 = v1 + v2;
</div></th></tr></tbody></table></div><aside class="prompt" data-type="note" data-title="" id="z7hbb6_1023"><p id="z7hbb6_1067">*: This was technically the definition until 2011. Technically there are these weird things called gl-values, pr-values, x-values, ...</p></aside><p id="z7hbb6_1024"><span id="z7hbb6_1068"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-collapse" data-lang="cpp" data-is-expanded="false" data-synopsis="int val = 2; // val: lvalue, 2: rvalue">
int val = 2; // val: lvalue, 2: rvalue
int* ptr = &val; // ptr: lvalue, &val: rvalue
std::vector<int> v1{1, 2, 3}; // v1: lvalue, {1, 2, 3}: rvalue
auto v4 = v1 + v2; // v4: lvalue, v1 + v2: rvalue => + returns a copy to a temporary
size_t size = v1.size(); // size: lvalue, v1.size(): rvalue
val = static_cast<int>(size); // val: lvalue, static_cast<int>(size): rvalue
// cast returns a copy of size
</div><aside class="prompt" data-type="warning" data-title="" id="z7hbb6_1026"><p id="z7hbb6_1069">An r-value reference is an alias to an r-value</p><p id="z7hbb6_1070">BUT the r-value reference itself is an l-value</p></aside><figure id="z7hbb6_1027"><img alt="Value References" src="Computer-Science-Study-Notes/c12-1.png" title="Value References" width="2340" height="609"></figure></section><section class="chapter"><h4 id="12-2-move-semantics" data-toc="12-2-move-semantics">12.2 Move Semantics</h4></section></section><section class="chapter"><h3 id="inheritance" data-toc="inheritance">13 Inheritance</h3><section class="chapter"><h4 id="13-1-namespace" data-toc="13-1-namespace">13.1 Namespace</h4><p id="z7hbb6_1074"><span id="z7hbb6_1079"><font style="color:#ff8c00">Namespace:</font></span> Namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e. names).</p><p id="z7hbb6_1075"><span id="z7hbb6_1080"><font style="color:#8a2be2">Goal:</font></span> To resolve identifier clash. The same identifier can be independently defined in multiple namespaces. That is, an identifier defined in one namespace may or may not have the same meaning as the same identifier defined in another namespace.</p><aside class="prompt" data-type="tip" data-title="" id="z7hbb6_1076"><p id="z7hbb6_1081">Here is an analogy from Wikipedia:</p><p id="z7hbb6_1082">Imagine that two companies, X and Y, each assign ID numbers to their employees. X should not have two employees with the same ID number, and likewise for Y; but it is not a problem for the same ID number to be used at both companies. For example, if Bill works for company X and Jane works for company Y, then it is not a problem for each of them to be employee #123.</p></aside><p id="z7hbb6_1077"><span id="z7hbb6_1083"><font style="color:#8a2be2">Most modern languages use namespaces to fix this.</font></span></p><div class="tabs" id="z7hbb6_1078" data-anchors="[c,java,javascript,python]"><div class="tabs__content" data-gtm="tab" id="c" data-title="C++"><div class="code-collapse" data-lang="cpp" data-title="C++" data-is-expanded="false" data-synopsis="#include <iostream>">
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3}; // std:: is namespace
for (int i : v) {
std::cout << i << std::endl;
}
return 0;
}
</div></div><div class="tabs__content" data-gtm="tab" id="python" data-title="Python"><div class="code-block" data-lang="python" data-title="Python">
import numpy as np
a = np.array([1, 2, 3]) // np. is namespace
</div></div><div class="tabs__content" data-gtm="tab" id="java" data-title="Java"><div class="code-collapse" data-lang="java" data-title="Java" data-is-expanded="false" data-synopsis="import java.util.ArrayList; // Java packages before identifier">
import java.util.ArrayList; // Java packages before identifier
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
for (int i : list) {
System.out.println(i);
}
}
}
</div></div><div class="tabs__content" data-gtm="tab" id="javascript" data-title="JavaScript"><div class="code-block" data-lang="javascript" data-title="JavaScript">
const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf8'); // fs. is namespace
</div></div></div></section><section class="chapter"><h4 id="13-1-overriding-and-overloading" data-toc="13-1-overriding-and-overloading">13.1 Overriding and Overloading</h4><p id="z7hbb6_1092"><span id="z7hbb6_1102"><font style="color:#8a2be2">Definition:</font></span></p><ul class="list _bullet" id="z7hbb6_1093"><li class="list__item" id="z7hbb6_1103"><p id="z7hbb6_1105"><span id="z7hbb6_1106"><font style="color:#ff8c00">Overloading</font></span>: Methods with the same name but different signature.</p></li><li class="list__item" id="z7hbb6_1104"><p id="z7hbb6_1107"><span id="z7hbb6_1108"><font style="color:#ff8c00">Overriding</font></span>: A subclass to provide a specific implementation of a method that is already provided by its parent class or interface.</p></li></ul><aside class="prompt" data-type="note" data-title="" id="z7hbb6_1094"><p id="z7hbb6_1109">This is an implementation of overloading in the same class.</p></aside><div class="code-collapse" data-lang="java" data-is-expanded="false" data-synopsis="// part of code from Quicksort">
// part of code from Quicksort
public static void sort(Comparable[] a) {
sort(a, 0, a.length - 1);
}
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) return;
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
</div><aside class="prompt" data-type="note" data-title="" id="z7hbb6_1096"><p id="z7hbb6_1110">This is an implementation of overloading in different classes.</p></aside><div class="code-collapse" data-lang="java" data-is-expanded="false" data-synopsis="class Shape {">
class Shape {
public void calculateArea(int side) {
System.out.println("Area of a square: " + (side * side));
}
}
class Rectangle extends Shape {
public void calculateArea(int length, int width) {
System.out.println("Area of a rectangle: " + (length * width));
}
}
public class Main {
public static void main(String[] args) {
Rectangle myRectangle = new Rectangle();
myRectangle.calculateArea(5); // Calls Shape's calculateArea (inherited)
myRectangle.calculateArea(4, 6); // Calls Rectangle's calculateArea (overloaded)
}
}
</div><aside class="prompt" data-type="note" data-title="" id="z7hbb6_1098"><p id="z7hbb6_1111">This is an implementation of overriding.</p></aside><div class="code-collapse" data-lang="java" data-is-expanded="false" data-synopsis="interface Animal {">
interface Animal {
void makeSound(); // Abstract method declaration
}
class Dog implements Animal { // Implementing the interface
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
class Cat implements Animal { // Implementing the interface
@Override