-
Notifications
You must be signed in to change notification settings - Fork 0
/
c-programming.html
1155 lines (992 loc) · 170 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-12-10T15:14:05.5787904"><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":1,"title":"7 Iterators","anchor":"#iterators"},{"id":"6-4-1-input-iterators","level":2,"title":"6.4.1 Input Iterators","anchor":"#6-4-1-input-iterators"},{"id":"6-4-2-output-iterators","level":2,"title":"6.4.2 Output Iterators","anchor":"#6-4-2-output-iterators"},{"id":"6-4-3-forward-iterators","level":2,"title":"6.4.3 Forward Iterators","anchor":"#6-4-3-forward-iterators"},{"id":"6-4-4-bidirectional-iterators","level":2,"title":"6.4.4 Bidirectional Iterators","anchor":"#6-4-4-bidirectional-iterators"},{"id":"6-4-5-random-access-iterators","level":2,"title":"6.4.5 Random Access Iterators","anchor":"#6-4-5-random-access-iterators"},{"id":"8-templates","level":1,"title":"8 Templates","anchor":"#8-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":"9-functions-and-algorithms","level":1,"title":"9 Functions and Algorithms","anchor":"#9-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":"10-classes-and-consts","level":1,"title":"10 Classes and Consts","anchor":"#10-classes-and-consts"},{"id":"10-1-classes","level":2,"title":"10.1 Classes","anchor":"#10-1-classes"},{"id":"10-2-consts","level":2,"title":"10.2 Consts","anchor":"#10-2-consts"},{"id":"11-operators","level":1,"title":"11 Operators","anchor":"#11-operators"},{"id":"11-1-basic-operators","level":2,"title":"11.1 Basic Operators","anchor":"#11-1-basic-operators"},{"id":"11-2-operator-overloading","level":2,"title":"11.2 Operator Overloading","anchor":"#11-2-operator-overloading"},{"id":"11-3-principle-of-least-astonishment-pola","level":2,"title":"11.3 Principle of Least Astonishment (POLA)","anchor":"#11-3-principle-of-least-astonishment-pola"},{"id":"11-4-interesting-operators","level":2,"title":"11.4 Interesting Operators","anchor":"#11-4-interesting-operators"},{"id":"12-special-member-functions","level":1,"title":"12 Special Member Functions","anchor":"#12-special-member-functions"},{"id":"12-1-copy-constructor-copy-assignment-operator","level":2,"title":"12.1 Copy Constructor \u0026 Copy Assignment Operator","anchor":"#12-1-copy-constructor-copy-assignment-operator"},{"id":"12-2-delete-operations","level":2,"title":"12.2 Delete Operations","anchor":"#12-2-delete-operations"},{"id":"12-3-rule-of-zero-three","level":2,"title":"12.3 Rule of Zero/Three","anchor":"#12-3-rule-of-zero-three"},{"id":"12-4-copy-elision-and-return-value-optimization-rvo","level":2,"title":"12.4 Copy Elision and Return Value Optimization (RVO)","anchor":"#12-4-copy-elision-and-return-value-optimization-rvo"},{"id":"13-move-semantics","level":1,"title":"13 Move Semantics","anchor":"#13-move-semantics"},{"id":"13-1-lvalues-rvalues","level":2,"title":"13.1 lvalues \u0026 rvalues","anchor":"#13-1-lvalues-rvalues"},{"id":"13-2-move-semantics","level":2,"title":"13.2 Move Semantics","anchor":"#13-2-move-semantics"},{"id":"inheritance","level":1,"title":"14 Inheritance","anchor":"#inheritance"},{"id":"14-1-namespace","level":2,"title":"14.1 Namespace","anchor":"#14-1-namespace"},{"id":"14-2-overriding-and-overloading","level":2,"title":"14.2 Overriding and Overloading","anchor":"#14-2-overriding-and-overloading"},{"id":"14-3-types-of-inheritance","level":2,"title":"14.3 Types of Inheritance","anchor":"#14-3-types-of-inheritance"},{"id":"modern-c","level":0,"title":"Ⅳ Modern C++","anchor":"#modern-c"},{"id":"15-raii","level":1,"title":"15 RAII","anchor":"#15-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="jg8lqw_14"><span id="jg8lqw_22"><font style="color:#8a2be2">Properties:</font></span></p><ul class="list _bullet" id="jg8lqw_15"><li class="list__item" id="jg8lqw_23"><p id="jg8lqw_25">C/C++ is a <span id="jg8lqw_26"><font style="color:#ff4500">compiled</font></span> language.</p></li><li class="list__item" id="jg8lqw_24"><p id="jg8lqw_27">C/C++ <span id="jg8lqw_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="jg8lqw_28"><li class="list__item" id="jg8lqw_30"><p id="jg8lqw_33">Unlike Java, which converts to architecture-independent bytecode (run by JVM => Java Virtual Machine).</p></li><li class="list__item" id="jg8lqw_31"><p id="jg8lqw_34">Unlike Python, which directly <span id="jg8lqw_35"><i>interprets</i></span> the code.</p></li><li class="list__item" id="jg8lqw_32"><p id="jg8lqw_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="jg8lqw_16"><span id="jg8lqw_37"><font style="color:#8a2be2">Compilation Advantages:</font></span></p><ul class="list _bullet" id="jg8lqw_17"><li class="list__item" id="jg8lqw_38"><p id="jg8lqw_40"><span id="jg8lqw_42"><font style="color:#ff00ff">Excellent run-time performance:</font></span></p><p id="jg8lqw_41">Generally much faster than Python or Java for comparable code because it <span id="jg8lqw_43"><font style="color:#ff4500">optimizes for the given architecture</font></span>.</p></li><li class="list__item" id="jg8lqw_39"><p id="jg8lqw_44"><span id="jg8lqw_46"><font style="color:#ff00ff">Fair compilation time:</font></span></p><p id="jg8lqw_45">Enhancements in compilation procedure (Makefiles) allow us to <span id="jg8lqw_47"><font style="color:#ff4500">recompile only the modified files</font></span>.</p></li></ul><p id="jg8lqw_18"><span id="jg8lqw_48"><font style="color:#8a2be2">Compilation Disadvantages:</font></span></p><ul class="list _bullet" id="jg8lqw_19"><li class="list__item" id="jg8lqw_49"><p id="jg8lqw_51">Compiled files, including the executable, are arcitecture-specific (CPU type and OS).</p><ul class="list _bullet" id="jg8lqw_52"><li class="list__item" id="jg8lqw_53"><p id="jg8lqw_55">Executable must be <span id="jg8lqw_56"><font style="color:#ff4500">rebuilt</font></span> on each new system.</p></li><li class="list__item" id="jg8lqw_54"><p id="jg8lqw_57">i.e. "porting your code" to a new architecture.</p></li></ul></li><li class="list__item" id="jg8lqw_50"><p id="jg8lqw_58">Instead of "Edit -> Run [repeat]" cycle, "Edit -> Compile -> Run [repeat]" iteration cycle can be slow.</p></li></ul><figure id="jg8lqw_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="jg8lqw_21"><p id="jg8lqw_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="jg8lqw_62"><thead><tr class="ijRowHead" id="jg8lqw_63"><th id="jg8lqw_70"><p>Fundamental Types</p></th><th id="jg8lqw_71"><p>Example</p></th><th id="jg8lqw_72"><p>Memory</p></th></tr></thead><tbody><tr id="jg8lqw_64"><td id="jg8lqw_73"><p>int</p></td><td id="jg8lqw_74"><div class="code-block" data-lang="cpp">int val = 5;</div></td><td id="jg8lqw_75"><p>32 bits (usually)</p></td></tr><tr id="jg8lqw_65"><td id="jg8lqw_77"><p>char</p></td><td id="jg8lqw_78"><div class="code-block" data-lang="cpp">char ch = 'F';</div></td><td id="jg8lqw_79"><p>8 bits (usually)</p></td></tr><tr id="jg8lqw_66"><td id="jg8lqw_81"><p>float</p></td><td id="jg8lqw_82"><div class="code-block" data-lang="cpp">float decimalVal1 = 5.0;</div></td><td id="jg8lqw_83"><p>32 bits (usually)</p></td></tr><tr id="jg8lqw_67"><td id="jg8lqw_85"><p>double</p></td><td id="jg8lqw_86"><div class="code-block" data-lang="cpp">double decimalVal2 = 5.0;</div></td><td id="jg8lqw_87"><p>64 bits (usually)</p></td></tr><tr id="jg8lqw_68"><td id="jg8lqw_89"><p>bool</p></td><td id="jg8lqw_90"><div class="code-block" data-lang="cpp">bool bVal = true;</div></td><td id="jg8lqw_91"><p>1 bit</p></td></tr><tr id="jg8lqw_69"><td id="jg8lqw_93"><p>std::string</p></td><td id="jg8lqw_94"><div class="code-block" data-lang="cpp">std::string str = "Haven";</div></td><td id="jg8lqw_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="jg8lqw_97"><span id="jg8lqw_101"><font style="color:#8a2be2">Definition:</font></span></p><p id="jg8lqw_98"><span id="jg8lqw_102"><font style="color:#ff8c00">Struct:</font></span> A <span id="jg8lqw_103"><b>struct</b></span> is a group of <span id="jg8lqw_104"><b>named variables</b></span>, each with their own type, that allows programmers to <span id="jg8lqw_105"><b>bundle different types</b></span> together!</p><p id="jg8lqw_99"><span id="jg8lqw_106"><font style="color:#8a2be2">Example:</font></span></p><div class="code-comparer" id="jg8lqw_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="jg8lqw_111">There are three types of initialization:</p><ol class="list _alpha-lower" id="jg8lqw_112" type="a"><li class="list__item" id="jg8lqw_115"><p id="jg8lqw_118"><span id="jg8lqw_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="jg8lqw_116"><p id="jg8lqw_121"><span id="jg8lqw_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="jg8lqw_117"><p id="jg8lqw_124"><span id="jg8lqw_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="jg8lqw_113"><span id="jg8lqw_127"><font style="color:#8a2be2">Advantages for Uniform Initialization:</font></span></p><ol class="list _decimal" id="jg8lqw_114" type="1"><li class="list__item" id="jg8lqw_128"><p id="jg8lqw_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="jg8lqw_129"><p id="jg8lqw_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="jg8lqw_132"><span id="jg8lqw_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="jg8lqw_134"><span id="jg8lqw_137"><font style="color:#8a2be2">A classic reference-copy bug:</font></span></p><div class="code-comparer" id="jg8lqw_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="jg8lqw_144">For more information on strings, please visit <a href="data-structures-and-algorithms-3.html#strings-in-java" id="jg8lqw_147" data-tooltip="Strings in Java">strings in Java</a>.</p><p id="jg8lqw_145"><span id="jg8lqw_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="jg8lqw_149"><li class="list__item" id="jg8lqw_154"><p id="jg8lqw_156">Constructors with initialtext in the buffer.</p></li><li class="list__item" id="jg8lqw_155"><p id="jg8lqw_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="jg8lqw_158"><span id="jg8lqw_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="jg8lqw_160"><span id="jg8lqw_163"><font style="color:#8a2be2">Positioning Functions:</font></span></p><ol class="list _decimal" id="jg8lqw_161" type="1"><li class="list__item" id="jg8lqw_164"><p id="jg8lqw_166"><span id="jg8lqw_169"><font style="color:#ff00ff">tellp()</font></span></p><p id="jg8lqw_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="jg8lqw_165"><p id="jg8lqw_170"><span id="jg8lqw_174"><font style="color:#ff00ff">seekp(pos)</font></span></p><p id="jg8lqw_171">Moves the put pointer to a specific position within the output string stream.</p><p id="jg8lqw_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="jg8lqw_175"><p id="jg8lqw_181">Types matter! Stream stops reading at any whitespace or any invalid character for the type.</p></aside><p id="jg8lqw_176"><span id="jg8lqw_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="jg8lqw_178"><span id="jg8lqw_183"><font style="color:#8a2be2">Positioning Functions:</font></span></p><ol class="list _decimal" id="jg8lqw_179" type="1"><li class="list__item" id="jg8lqw_184"><p id="jg8lqw_186"><span id="jg8lqw_189"><font style="color:#ff00ff">tellg()</font></span></p><p id="jg8lqw_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="jg8lqw_185"><p id="jg8lqw_190"><span id="jg8lqw_194"><font style="color:#ff00ff">seekg(pos)</font></span></p><p id="jg8lqw_191">Moves the put pointer to a specific position within the output string stream.</p><p id="jg8lqw_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="jg8lqw_180"><p id="jg8lqw_195">Two data types:</p><ol class="list _decimal" id="jg8lqw_196" type="1"><li class="list__item" id="jg8lqw_199"><p id="jg8lqw_201"><span id="jg8lqw_202"><font style="color:#ff00ff">streampos:</font></span> Represents the position of the get pointer.</p></li><li class="list__item" id="jg8lqw_200"><p id="jg8lqw_203"><span id="jg8lqw_204"><font style="color:#ff00ff">streamoff:</font></span> Represents the difference (offset) between two streampos values.</p></li></ol><p id="jg8lqw_197"><span id="jg8lqw_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="jg8lqw_207"><li class="list__item" id="jg8lqw_211"><p id="jg8lqw_214"><span id="jg8lqw_215"><font style="color:#ff00ff">is:</font></span> The input stream from which to read.</p></li><li class="list__item" id="jg8lqw_212"><p id="jg8lqw_216"><span id="jg8lqw_217"><font style="color:#ff00ff">str:</font></span> The string where the read line will be stored.</p></li><li class="list__item" id="jg8lqw_213"><p id="jg8lqw_218"><span id="jg8lqw_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="jg8lqw_208"><p id="jg8lqw_220">getline() <span id="jg8lqw_221"><font style="color:#ff4500">consumes</font></span> the delim character!</p></aside><p id="jg8lqw_209"><span id="jg8lqw_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="jg8lqw_223" type="a"><li class="list__item" id="jg8lqw_227"><p id="jg8lqw_231"><span id="jg8lqw_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="jg8lqw_228"><p id="jg8lqw_233"><span id="jg8lqw_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="jg8lqw_229"><p id="jg8lqw_235"><span id="jg8lqw_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="jg8lqw_230"><p id="jg8lqw_237"><span id="jg8lqw_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="jg8lqw_224"><p id="jg8lqw_239">Good and bad are not opposites! (e.g. type mismatch)</p><p id="jg8lqw_240">Good and fail are not opposites! (e.g. end of file)</p><p id="jg8lqw_241">Fail and EOF are normally the ones you will be checking.</p></aside><p id="jg8lqw_225"><span id="jg8lqw_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="jg8lqw_243"><span id="jg8lqw_250"><font style="color:#8a2be2">There are four standard iostreams</font></span></p><ul class="list _bullet" id="jg8lqw_244"><li class="list__item" id="jg8lqw_251"><p id="jg8lqw_255"><span id="jg8lqw_256"><font style="color:#ff00ff">cout:</font></span> Standard Output Stream .</p></li><li class="list__item" id="jg8lqw_252"><p id="jg8lqw_257"><span id="jg8lqw_258"><font style="color:#ff00ff">cin:</font></span> Standard Input Stream (buffered).</p></li><li class="list__item" id="jg8lqw_253"><p id="jg8lqw_259"><span id="jg8lqw_260"><font style="color:#ff00ff">cerr (Standard Error Stream):</font></span> used to output errors (unbuffered).</p></li><li class="list__item" id="jg8lqw_254"><p id="jg8lqw_261"><span id="jg8lqw_262"><font style="color:#ff00ff">clog (Standard Logging Stream):</font></span> used for non-critical event logging (buffered).</p></li></ul><p id="jg8lqw_245"><span id="jg8lqw_263"><font style="color:#8a2be2">cin</font></span></p><ul class="list _bullet" id="jg8lqw_246"><li class="list__item" id="jg8lqw_264"><p id="jg8lqw_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="jg8lqw_265"><p id="jg8lqw_268">The position pointer skips whitespace <span id="jg8lqw_269"><font style="color:#ff4500">after</font></span> the token with each >> operation.</p></li><li class="list__item" id="jg8lqw_266"><p id="jg8lqw_270">The position pointer does the following:</p><ul class="list _bullet" id="jg8lqw_271"><li class="list__item" id="jg8lqw_272"><p id="jg8lqw_274">consume all whitespaces (spaces, newlines, '\t', '\n', etc .)</p></li><li class="list__item" id="jg8lqw_273"><p id="jg8lqw_275">reads as many characters until:</p><ul class="list _bullet" id="jg8lqw_276"><li class="list__item" id="jg8lqw_277"><p id="jg8lqw_280">a whitespace is reached, or...</p></li><li class="list__item" id="jg8lqw_278"><p id="jg8lqw_281">for primitives, the maximum number of bytes necessary to form a valid variable.</p></li><li class="list__item" id="jg8lqw_279"><p id="jg8lqw_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="jg8lqw_247"><span id="jg8lqw_283"><font style="color:#cd5c5c">Examples</font></span></p><div class="code-comparer" id="jg8lqw_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="jg8lqw_249"><p id="jg8lqw_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="jg8lqw_287"><span id="jg8lqw_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="jg8lqw_289"><span id="jg8lqw_294"><font style="color:#8a2be2">Input File Streams & Output File Streams</font></span></p><div class="table-wrapper"><table class="left_header wide" id="jg8lqw_290"><thead><tr class="ijRowHead" id="jg8lqw_295"><th id="jg8lqw_301"></th><th id="jg8lqw_302"><p>ifstream</p></th><th id="jg8lqw_303"><p>ofstream</p></th></tr></thead><tbody><tr id="jg8lqw_296"><th id="jg8lqw_304"><p>Purpose</p></th><td id="jg8lqw_305"><p>Input from a file</p></td><td id="jg8lqw_306"><p>Output to a file</p></td></tr><tr id="jg8lqw_297"><th id="jg8lqw_307"><p>Mode</p></th><td id="jg8lqw_308"><p>Opens a file in read mode</p></td><td id="jg8lqw_309"><p>Opens a file in write mode</p></td></tr><tr id="jg8lqw_298"><th id="jg8lqw_310"><p>Default behavior</p></th><td id="jg8lqw_311"><p>If the file doesn't exist, it fails to open.</p></td><td id="jg8lqw_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="jg8lqw_299"><th id="jg8lqw_313"><p>Operators</p></th><td id="jg8lqw_314"><p>Primarily used with the extraction operator (>>) to read data from the file.</p></td><td id="jg8lqw_315"><p>Primarily used with the insertion operator (<<) to write data to the file.</p></td></tr><tr id="jg8lqw_300"><th id="jg8lqw_316"><p>Similarities</p></th><td id="jg8lqw_317" colspan="2"><ol class="list _alpha-lower" id="jg8lqw_318" type="a"><li class="list__item" id="jg8lqw_319"><p id="jg8lqw_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="jg8lqw_320"><p id="jg8lqw_322">Both inherit properties and methods from the base class fstream .</p></li></ol></td></tr></tbody></table></div><p id="jg8lqw_291"><span id="jg8lqw_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="jg8lqw_329"><li class="list__item" id="jg8lqw_331"><p id="jg8lqw_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="jg8lqw_332"><p id="jg8lqw_334">In libraries there is a common name for a type within each class. Example:</p><ul class="list _bullet" id="jg8lqw_335"><li class="list__item" id="jg8lqw_336"><p id="jg8lqw_338">vector::iterator, map::iterator, string::iterator</p></li><li class="list__item" id="jg8lqw_337"><p id="jg8lqw_339">vector::reference, map::reference, string::reference</p></li></ul></li></ul><aside class="prompt" data-type="warning" data-title="" id="jg8lqw_330"><p id="jg8lqw_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="jg8lqw_341">A pair is simply two objects bundled together.</p><aside class="prompt" data-type="note" data-title="" id="jg8lqw_342"><p id="jg8lqw_345">Remember to include < utility > and < tuple ></p></aside><p id="jg8lqw_343"><span id="jg8lqw_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="jg8lqw_347"><span id="jg8lqw_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="jg8lqw_351"><span id="jg8lqw_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="jg8lqw_352"><span id="jg8lqw_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="jg8lqw_354"><p id="jg8lqw_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="jg8lqw_359">Create type aliases with the using keyword.</p><div class="code-comparer" id="jg8lqw_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="jg8lqw_364">The <span id="jg8lqw_371"><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="jg8lqw_365">The <span id="jg8lqw_372"><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="jg8lqw_366"><p id="jg8lqw_373">The STL and the C++ Standard Library are two distinct entities.</p><p id="jg8lqw_374">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="jg8lqw_375">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="jg8lqw_379"><span id="jg8lqw_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="jg8lqw_380"><li class="list__item" id="jg8lqw_384"><p id="jg8lqw_389"><code class="code" id="jg8lqw_390">std::vector<T></code></p></li><li class="list__item" id="jg8lqw_385"><p id="jg8lqw_391"><code class="code" id="jg8lqw_392">std::deque<T></code></p></li><li class="list__item" id="jg8lqw_386"><p id="jg8lqw_393"><code class="code" id="jg8lqw_394">std::array<T></code></p></li><li class="list__item" id="jg8lqw_387"><p id="jg8lqw_395"><code class="code" id="jg8lqw_396">std::list<T></code></p></li><li class="list__item" id="jg8lqw_388"><p id="jg8lqw_397"><code class="code" id="jg8lqw_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="jg8lqw_399"><span id="jg8lqw_408"><font style="color:#ff8c00">Vector:</font></span> An array with changeable size.</p><p id="jg8lqw_400"><span id="jg8lqw_409"><font style="color:#cd5c5c">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="jg8lqw_402"><thead><tr class="ijRowHead" id="jg8lqw_410"><th id="jg8lqw_413"></th><th id="jg8lqw_414"><p><code class="code" id="jg8lqw_416">vec[index]</code></p></th><th id="jg8lqw_415"><p><code class="code" id="jg8lqw_417">vec.at(index)</code></p></th></tr></thead><tbody><tr id="jg8lqw_411"><th id="jg8lqw_418"><p>Bounds Checking</p></th><td id="jg8lqw_419"><p>No</p></td><td id="jg8lqw_420"><p>Yes</p></td></tr><tr id="jg8lqw_412"><th id="jg8lqw_421"><p>Speed</p></th><td id="jg8lqw_422"><p>Fast</p></td><td id="jg8lqw_423"><p>Slow</p></td></tr></tbody></table></div><aside class="prompt" data-type="warning" data-title="" id="jg8lqw_403"><p id="jg8lqw_424">If you write your program <span id="jg8lqw_426"><font style="color:#adff2f">correctly</font></span>, bounds checking will just <span id="jg8lqw_427"><font style="color:#ff4500">slow</font></span> you down.</p><p id="jg8lqw_425">Use range-based for & <code class="code" id="jg8lqw_428">const auto&</code> when possible.</p></aside><p id="jg8lqw_404"><span id="jg8lqw_429"><font style="color:#8a2be2">Advantages:</font></span></p><ul class="list _bullet" id="jg8lqw_405"><li class="list__item" id="jg8lqw_430"><p id="jg8lqw_432">Fast, lightweight & intuitive.</p></li><li class="list__item" id="jg8lqw_431"><p id="jg8lqw_433">Grow efficiently <span id="jg8lqw_434"><font style="color:#adff2f">in one direction</font></span>.</p></li></ul><p id="jg8lqw_406"><span id="jg8lqw_435"><font style="color:#8a2be2">Disadvantages:</font></span></p><ul class="list _bullet" id="jg8lqw_407"><li class="list__item" id="jg8lqw_436"><p id="jg8lqw_437">cannot <code class="code" id="jg8lqw_438">push_front</code>!</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="jg8lqw_439"><span id="jg8lqw_448"><font style="color:#ff8c00">Deque:</font></span> A deque is a doubly ended queue.</p><p id="jg8lqw_440"><span id="jg8lqw_449"><font style="color:#8a2be2">Implementation</font></span></p><p id="jg8lqw_441">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="jg8lqw_442">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><figure id="jg8lqw_443"><img alt="Deque Implementation" src="Computer-Science-Study-Notes/c6-1.png" title="Deque Implementation" width="6932" height="1486"></figure><p id="jg8lqw_444"><span id="jg8lqw_450"><font style="color:#8a2be2">Advantages:</font></span></p><ul class="list _bullet" id="jg8lqw_445"><li class="list__item" id="jg8lqw_451"><p id="jg8lqw_452">Can <code class="code" id="jg8lqw_453">push_front</code>!</p></li></ul><p id="jg8lqw_446"><span id="jg8lqw_454"><font style="color:#8a2be2">Disadvantages:</font></span></p><ul class="list _bullet" id="jg8lqw_447"><li class="list__item" id="jg8lqw_455"><p id="jg8lqw_456">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="jg8lqw_457" type="a"><li class="list__item" id="jg8lqw_458"><p id="jg8lqw_460"><span id="jg8lqw_462"><font style="color:#ff00ff">Stacks:</font></span></p><ul class="list _bullet" id="jg8lqw_461"><li class="list__item" id="jg8lqw_463"><p id="jg8lqw_465">Just limit the functionality of a vector/deque to only allow <code class="code" id="jg8lqw_466">push_back</code> and <code class="code" id="jg8lqw_467">pop_back</code>.</p></li><li class="list__item" id="jg8lqw_464"><p id="jg8lqw_468">The standard containers <code class="code" id="jg8lqw_469">std::vector</code> (including <code class="code" id="jg8lqw_470">std::vector<bool></code>), <code class="code" id="jg8lqw_471">std::deque</code> and <code class="code" id="jg8lqw_472">std::list</code> satisfy these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container <code class="code" id="jg8lqw_473">std::deque</code> is used.</p></li></ul></li><li class="list__item" id="jg8lqw_459"><p id="jg8lqw_474"><span id="jg8lqw_476"><font style="color:#ff00ff">Queues:</font></span></p><ul class="list _bullet" id="jg8lqw_475"><li class="list__item" id="jg8lqw_477"><p id="jg8lqw_479">The standard containers <code class="code" id="jg8lqw_480">std::deque</code> and <code class="code" id="jg8lqw_481">std::list</code> satisfy these requirements.</p></li><li class="list__item" id="jg8lqw_478"><p id="jg8lqw_482">Just limit the functionality of a deque to only allow <code class="code" id="jg8lqw_483">push_back</code> and <code class="code" id="jg8lqw_484">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="jg8lqw_485"><span id="jg8lqw_489"><font style="color:#ff8c00">Associative containers:</font></span> Data is accessed using the <span id="jg8lqw_490"><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><aside class="prompt" data-type="warning" data-title="" id="jg8lqw_487"><p id="jg8lqw_491"><code class="code" id="jg8lqw_492">std::map<K, V></code> stores <code class="code" id="jg8lqw_493">std::pair<const K, V></code></p></aside><aside class="prompt" data-type="tip" data-title="" id="jg8lqw_488"><p id="jg8lqw_494">For more information on the implementation of these assocative adaptators, please visit <a href="data-structures-and-algorithms-1.html" id="jg8lqw_495" data-tooltip="Data Structures and Algorithms">Data Structures and Algorithms</a> for more!</p></aside></section></section><section class="chapter"><h3 id="iterators" data-toc="iterators">7 Iterators</h3><p id="jg8lqw_496"><span id="jg8lqw_506"><font style="color:#8a2be2">Four iterator operations:</font></span></p><ul class="list _bullet" id="jg8lqw_497"><li class="list__item" id="jg8lqw_507"><p id="jg8lqw_511"><span id="jg8lqw_513"><font style="color:#ff00ff">Create iterator:</font></span></p><p id="jg8lqw_512"><code class="code" id="jg8lqw_514">std::set<int>::iterator iter = mySet.begin()</code></p></li><li class="list__item" id="jg8lqw_508"><p id="jg8lqw_515"><span id="jg8lqw_517"><font style="color:#ff00ff">Dereference iterator to read value currently pointed to:</font></span></p><p id="jg8lqw_516"><code class="code" id="jg8lqw_518">int val = *iter</code></p></li><li class="list__item" id="jg8lqw_509"><p id="jg8lqw_519"><span id="jg8lqw_521"><font style="color:#ff00ff">Advance iterator:</font></span></p><p id="jg8lqw_520"><code class="code" id="jg8lqw_522">iter++</code>; or <code class="code" id="jg8lqw_523">++iter</code></p></li><li class="list__item" id="jg8lqw_510"><p id="jg8lqw_524"><span id="jg8lqw_525"><font style="color:#ff00ff">Compare against another iterator</font></span> (especially <code class="code" id="jg8lqw_526">.end()</code> iterator)</p></li></ul><p id="jg8lqw_498"><span id="jg8lqw_527"><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"><h4 id="6-4-1-input-iterators" data-toc="6-4-1-input-iterators">6.4.1 Input Iterators</h4><p id="jg8lqw_528">For sequential, single-pass input.</p><p id="jg8lqw_529">Read only, i.e. can only be dereferenced on <span id="jg8lqw_532"><font style="color:#ff4500">right</font></span> side of expression.</p><p id="jg8lqw_530"><span id="jg8lqw_533"><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"><h4 id="6-4-2-output-iterators" data-toc="6-4-2-output-iterators">6.4.2 Output Iterators</h4><p id="jg8lqw_534">For sequential, single-pass output.</p><p id="jg8lqw_535">Read only, i.e. can only be dereferenced on <span id="jg8lqw_538"><font style="color:#ff4500">left</font></span> side of expression.</p><p id="jg8lqw_536"><span id="jg8lqw_539"><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"><h4 id="6-4-3-forward-iterators" data-toc="6-4-3-forward-iterators">6.4.3 Forward Iterators</h4><p id="jg8lqw_540">Combines input and output, plus can make multiple passes.</p><p id="jg8lqw_541">Can read from and write to (if not const iterator).</p><p id="jg8lqw_542"><span id="jg8lqw_544"><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"><h4 id="6-4-4-bidirectional-iterators" data-toc="6-4-4-bidirectional-iterators">6.4.4 Bidirectional Iterators</h4><p id="jg8lqw_545">Same as forward iterators, plus can go backwards with the decrement operator (--).</p><p id="jg8lqw_546"><span id="jg8lqw_547"><font style="color:#8a2be2">Use cases:</font></span> <code class="code" id="jg8lqw_548">std::map</code>, <code class="code" id="jg8lqw_549">std::set</code>, <code class="code" id="jg8lqw_550">std::list</code></p></section><section class="chapter"><h4 id="6-4-5-random-access-iterators" data-toc="6-4-5-random-access-iterators">6.4.5 Random Access Iterators</h4><p id="jg8lqw_551">Same as bidirectional iterators, plus can be implemented or decremented by arbitrary amounts using + and -.</p><p id="jg8lqw_552"><span id="jg8lqw_553"><font style="color:#8a2be2">Use cases:</font></span> <code class="code" id="jg8lqw_554">std::vector</code>, <code class="code" id="jg8lqw_555">std::deque</code>, <code class="code" id="jg8lqw_556">std::string</code></p></section></section><section class="chapter"><h3 id="8-templates" data-toc="8-templates">8 Templates</h3><p id="jg8lqw_557">We can use templates to keep the logic, but change the type!</p><section class="chapter"><h4 id="7-1-template-functions" data-toc="7-1-template-functions">7.1 Template Functions</h4><p id="jg8lqw_560"><span id="jg8lqw_572"><font style="color:#cd5c5c">Example</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="jg8lqw_562">The following code:</p><div class="code-block" data-lang="cpp">
my_minmax(cout, cout);
</div><p id="jg8lqw_564"><span id="jg8lqw_573"><font style="color:#ff00ff">Semantic error:</font></span> you can't call operator < on two streams.</p><p id="jg8lqw_565"><span id="jg8lqw_574"><font style="color:#ff00ff">Conceptual error:</font></span> you can't find the min or max of two streams.</p><p id="jg8lqw_566">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="jg8lqw_568">Problem lies in indexing <code class="code" id="jg8lqw_575">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="jg8lqw_570">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="jg8lqw_577"><p id="jg8lqw_581">Add template declaration for class</p></li><li class="list__item" id="jg8lqw_578"><p id="jg8lqw_582">Add all the member type aliases</p></li><li class="list__item" id="jg8lqw_579"><p id="jg8lqw_583">Add the template declaration to every single class member</p></li><li class="list__item" id="jg8lqw_580"><p id="jg8lqw_584">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="9-functions-and-algorithms" data-toc="9-functions-and-algorithms">9 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="jg8lqw_588"><li class="list__item" id="jg8lqw_596"><p id="jg8lqw_600"><code class="code" id="jg8lqw_601">auto</code>: We don't know the type, ask compiler.</p></li><li class="list__item" id="jg8lqw_597"><p id="jg8lqw_602"><code class="code" id="jg8lqw_603">[limit]</code>: Capture clause, gives access to outside variables.</p></li><li class="list__item" id="jg8lqw_598"><p id="jg8lqw_604"><code class="code" id="jg8lqw_605">(auto)</code>: Parameter list, can use auto!</p></li><li class="list__item" id="jg8lqw_599"><p id="jg8lqw_606"><code class="code" id="jg8lqw_607">-> bool</code>: Return type, optional.</p></li></ul><p id="jg8lqw_589">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="jg8lqw_591"><p id="jg8lqw_608"><code class="code" id="jg8lqw_613">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="jg8lqw_610">In this context, <code class="code" id="jg8lqw_614">std::function<int(int, int)></code> can store any callable object as long as it matches the signature.</p><p id="jg8lqw_611"><span id="jg8lqw_615"><font style="color:#8a2be2">Benefit:</font></span></p><ol class="list _alpha-lower" id="jg8lqw_612" type="a"><li class="list__item" id="jg8lqw_616"><p id="jg8lqw_618"><span id="jg8lqw_619"><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="jg8lqw_620">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="jg8lqw_617"><p id="jg8lqw_621"><span id="jg8lqw_622"><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="jg8lqw_592"><code class="code" id="jg8lqw_623">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="jg8lqw_594"><li class="list__item" id="jg8lqw_624"><p id="jg8lqw_627"><code class="code" id="jg8lqw_628">std::placeholders::_1</code> means "take the first argument passed to operation".</p></li><li class="list__item" id="jg8lqw_625"><p id="jg8lqw_629"><code class="code" id="jg8lqw_630">std::placeholders::_2</code> means "take the second argument passed to operation".</p></li><li class="list__item" id="jg8lqw_626"><p id="jg8lqw_631">4 is the third argument of <code class="code" id="jg8lqw_632">multiplyAndAdd</code>.</p></li></ul><aside class="prompt" data-type="warning" data-title="" id="jg8lqw_595"><p id="jg8lqw_633">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="jg8lqw_639"><span id="jg8lqw_647"><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="jg8lqw_641"><span id="jg8lqw_648"><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="jg8lqw_643"><span id="jg8lqw_649"><font style="color:#8a2be2">Parameters:</font></span></p><ol class="list _decimal" id="jg8lqw_644" type="1"><li class="list__item" id="jg8lqw_650"><p id="jg8lqw_653"><span id="jg8lqw_654"><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="jg8lqw_651"><p id="jg8lqw_655"><span id="jg8lqw_656"><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="jg8lqw_652"><p id="jg8lqw_657"><span id="jg8lqw_658"><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="jg8lqw_645"><span id="jg8lqw_659"><font style="color:#8a2be2">Important notes:</font></span></p><ul class="list _bullet" id="jg8lqw_646"><li class="list__item" id="jg8lqw_660"><p id="jg8lqw_663">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="jg8lqw_661"><p id="jg8lqw_665">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="jg8lqw_662"><p id="jg8lqw_667"><span id="jg8lqw_668"><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="jg8lqw_670"><span id="jg8lqw_678"><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="jg8lqw_672"><span id="jg8lqw_679"><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="jg8lqw_674"><span id="jg8lqw_680"><font style="color:#8a2be2">Parameters:</font></span></p><ol class="list _decimal" id="jg8lqw_675" type="1"><li class="list__item" id="jg8lqw_681"><p id="jg8lqw_685"><span id="jg8lqw_686"><font style="color:#ff00ff">first:</font></span> Iterator to the beginning of the range.</p></li><li class="list__item" id="jg8lqw_682"><p id="jg8lqw_687"><span id="jg8lqw_688"><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="jg8lqw_683"><p id="jg8lqw_689"><span id="jg8lqw_690"><font style="color:#ff00ff">last:</font></span> Iterator to one past the end of the range.</p></li><li class="list__item" id="jg8lqw_684"><p id="jg8lqw_691"><span id="jg8lqw_692"><font style="color:#ff00ff">comp (optional):</font></span> A binary comparison function, similar to std::sort.</p></li></ol><p id="jg8lqw_676"><span id="jg8lqw_693"><font style="color:#8a2be2">Important notes:</font></span></p><ul class="list _bullet" id="jg8lqw_677"><li class="list__item" id="jg8lqw_694"><p id="jg8lqw_697">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="jg8lqw_695"><p id="jg8lqw_699">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="jg8lqw_696"><p id="jg8lqw_702"><span id="jg8lqw_703"><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="jg8lqw_705"><span id="jg8lqw_711"><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="jg8lqw_707"><span id="jg8lqw_712"><font style="color:#8a2be2">Parameters:</font></span></p><ol class="list _decimal" id="jg8lqw_708" type="1"><li class="list__item" id="jg8lqw_713"><p id="jg8lqw_719"><span id="jg8lqw_720"><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="jg8lqw_714"><p id="jg8lqw_721"><span id="jg8lqw_722"><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="jg8lqw_715"><p id="jg8lqw_723"><span id="jg8lqw_724"><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="jg8lqw_716"><p id="jg8lqw_725"><span id="jg8lqw_726"><font style="color:#ff00ff">UnaryPredicate:</font></span> A template parameter representing the type of the predicate function.</p></li><li class="list__item" id="jg8lqw_717"><p id="jg8lqw_727"><span id="jg8lqw_728"><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="jg8lqw_718"><ul class="list _bullet" id="jg8lqw_729"><li class="list__item" id="jg8lqw_730"><p id="jg8lqw_732">true: The element satisfies the partitioning criterion.</p></li><li class="list__item" id="jg8lqw_731"><p id="jg8lqw_733">false: The element does not satisfy the criterion.</p></li></ul></li></ol><p id="jg8lqw_709"><span id="jg8lqw_734"><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="jg8lqw_735"><span id="jg8lqw_740"><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="jg8lqw_737" type="1"><li class="list__item" id="jg8lqw_741"><p id="jg8lqw_749"><span id="jg8lqw_750"><font style="color:#ff00ff">InputIterator:</font></span> Type of iterator used for the input range.</p></li><li class="list__item" id="jg8lqw_742"><p id="jg8lqw_751"><span id="jg8lqw_752"><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="jg8lqw_743"><p id="jg8lqw_753"><span id="jg8lqw_754"><font style="color:#ff00ff">first (InputIterator):</font></span> An iterator to the beginning of the input range.</p></li><li class="list__item" id="jg8lqw_744"><p id="jg8lqw_755"><span id="jg8lqw_756"><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="jg8lqw_745"><p id="jg8lqw_757"><span id="jg8lqw_758"><font style="color:#ff00ff">result (OutputIterator):</font></span> An iterator to the beginning of the output range.</p></li><li class="list__item" id="jg8lqw_746"><p id="jg8lqw_759"><span id="jg8lqw_760"><font style="color:#ff00ff">UnaryPredicate:</font></span> Type of the predicate function.</p></li><li class="list__item" id="jg8lqw_747"><p id="jg8lqw_761"><span id="jg8lqw_762"><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="jg8lqw_748"><ul class="list _bullet" id="jg8lqw_763"><li class="list__item" id="jg8lqw_764"><p id="jg8lqw_766">true: Copy the element to the output range.</p></li><li class="list__item" id="jg8lqw_765"><p id="jg8lqw_767">false: Skip the element.</p></li></ul></li></ol><p id="jg8lqw_738"><span id="jg8lqw_768"><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="jg8lqw_769"><span id="jg8lqw_772"><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="jg8lqw_771" type="1"><li class="list__item" id="jg8lqw_773"><p id="jg8lqw_779"><span id="jg8lqw_780"><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="jg8lqw_774"><p id="jg8lqw_781"><span id="jg8lqw_782"><font style="color:#ff00ff">first (ForwardIterator):</font></span> An iterator to the beginning of the range.</p></li><li class="list__item" id="jg8lqw_775"><p id="jg8lqw_783"><span id="jg8lqw_784"><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="jg8lqw_776"><p id="jg8lqw_785"><span id="jg8lqw_786"><font style="color:#ff00ff">UnaryPredicate:</font></span> Type of the predicate function.</p></li><li class="list__item" id="jg8lqw_777"><p id="jg8lqw_787"><span id="jg8lqw_788"><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="jg8lqw_778"><ul class="list _bullet" id="jg8lqw_789"><li class="list__item" id="jg8lqw_790"><p id="jg8lqw_792">true: The element should be "removed."</p></li><li class="list__item" id="jg8lqw_791"><p id="jg8lqw_793">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="10-classes-and-consts" data-toc="10-classes-and-consts">10 Classes and Consts</h3><section class="chapter"><h4 id="10-1-classes" data-toc="10-1-classes">10.1 Classes</h4><p id="jg8lqw_802"><span id="jg8lqw_813"><font style="color:#8a2be2">Definitions:</font></span></p><ul class="list _bullet" id="jg8lqw_803"><li class="list__item" id="jg8lqw_814"><p id="jg8lqw_822"><span id="jg8lqw_823"><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="jg8lqw_815"><p id="jg8lqw_824"><span id="jg8lqw_825"><font style="color:#ff8c00">Object:</font></span> Entity that combines state and behavior, instance of a class.</p></li><li class="list__item" id="jg8lqw_816"><p id="jg8lqw_826"><span id="jg8lqw_827"><font style="color:#ff8c00">Member variables (instance variables, fields):</font></span> Define state inside each object.</p></li><li class="list__item" id="jg8lqw_817"><p id="jg8lqw_828"><span id="jg8lqw_829"><font style="color:#ff8c00">Member functions (methods):</font></span> Define behavior inside each object.</p></li><li class="list__item" id="jg8lqw_818"><p id="jg8lqw_830"><span id="jg8lqw_831"><font style="color:#ff8c00">Constructor:</font></span> Initializes the state of newly created objects.</p></li><li class="list__item" id="jg8lqw_819"><p id="jg8lqw_832"><span id="jg8lqw_834"><font style="color:#ff8c00">Destructor:</font></span> Called when the object is deleted by the program.</p><ul class="list _bullet" id="jg8lqw_833"><li class="list__item" id="jg8lqw_835"><p id="jg8lqw_837">Delete any pointers stored as private members.</p></li><li class="list__item" id="jg8lqw_836"><p id="jg8lqw_838">delete[] any arrays stored as private members.</p></li></ul></li><li class="list__item" id="jg8lqw_820"><p id="jg8lqw_839"><span id="jg8lqw_840"><font style="color:#ff8c00">Client code:</font></span> Code that uses the objects defind.</p></li><li class="list__item" id="jg8lqw_821"><p id="jg8lqw_841"><span id="jg8lqw_842"><font style="color:#ff8c00">Encapsulation:</font></span> Hiding implementation details from the client code.</p></li></ul><p id="jg8lqw_804">C++ separates classes into two kinds of files:</p><ul class="list _bullet" id="jg8lqw_805"><li class="list__item" id="jg8lqw_843"><p id="jg8lqw_845"><span id="jg8lqw_846"><font style="color:#ff00ff">Header File</font></span> (<span id="jg8lqw_847"><font style="color:#ff4500">.h</font></span>, .hh, .hpp): Containing the interface (declarations).</p></li><li class="list__item" id="jg8lqw_844"><p id="jg8lqw_848"><span id="jg8lqw_849"><font style="color:#ff00ff">Source File</font></span> (<span id="jg8lqw_850"><font style="color:#ff4500">.cpp</font></span>, .cc, .cxx, .c++, .C): Containing definitions (method bodies).</p></li></ul><p id="jg8lqw_806">Classes have <span id="jg8lqw_851"><font style="color:#ff4500">three</font></span> main parts:</p><ul class="list _bullet" id="jg8lqw_807"><li class="list__item" id="jg8lqw_852"><p id="jg8lqw_855"><span id="jg8lqw_856"><font style="color:#ff00ff">Constructor and destructor</font></span></p></li><li class="list__item" id="jg8lqw_853"><p id="jg8lqw_857"><span id="jg8lqw_858"><font style="color:#ff00ff">Member variables</font></span></p></li><li class="list__item" id="jg8lqw_854"><p id="jg8lqw_859"><span id="jg8lqw_860"><font style="color:#ff00ff">Member functions</font></span></p></li></ul><p id="jg8lqw_808"><span id="jg8lqw_861"><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="jg8lqw_810"><span id="jg8lqw_862"><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="jg8lqw_812"><p id="jg8lqw_863">Why so many extensions?</p><p id="jg8lqw_864">Depend on the compilers!</p><ul class="list _bullet" id="jg8lqw_865"><li class="list__item" id="jg8lqw_866"><p id="jg8lqw_869">Historically, used .C</p></li><li class="list__item" id="jg8lqw_867"><p id="jg8lqw_870">Now, Unix most uses <span id="jg8lqw_871"><font style="color:#ff4500">.cc</font></span>, and outside Unix mostly uses <span id="jg8lqw_872"><font style="color:#ff4500">.cpp</font></span></p></li><li class="list__item" id="jg8lqw_868"><p id="jg8lqw_873">.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="10-2-consts" data-toc="10-2-consts">10.2 Consts</h4><p id="jg8lqw_874"><span id="jg8lqw_883"><font style="color:#ff8c00">Consts:</font></span> A qualifier for objects that declares they cannot be modified.</p><p id="jg8lqw_875">Consts help us find bugs, and allow us to reason about whether a variable will be changed.</p><p id="jg8lqw_876">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="jg8lqw_877"><span id="jg8lqw_884"><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="jg8lqw_879"><span id="jg8lqw_885"><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="jg8lqw_887"><p id="jg8lqw_888">When in doubt, read from right to left!</p><p id="jg8lqw_889">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="11-operators" data-toc="11-operators">11 Operators</h3><section class="chapter"><h4 id="11-1-basic-operators" data-toc="11-1-basic-operators">11.1 Basic Operators</h4><p id="jg8lqw_895">There are 40 (+4) operators you can overload!</p><figure id="jg8lqw_896"><img alt="Operators" src="Computer-Science-Study-Notes/c8-1.png" title="Operators" width="1899" height="1141"></figure><p id="jg8lqw_897"><span id="jg8lqw_901"><font style="color:#8a2be2">Examples for default operators behaviors:</font></span></p><div class="code-comparer" id="jg8lqw_898" 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="jg8lqw_899">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="11-2-operator-overloading" data-toc="11-2-operator-overloading">11.2 Operator Overloading</h4><p id="jg8lqw_904"><span id="jg8lqw_913"><font style="color:#8a2be2">General rule of Thumb:</font></span> (Member & Non-Member)</p><ol class="list _decimal" id="jg8lqw_905" type="1"><li class="list__item" id="jg8lqw_914"><p>Some operators must be implemented as members (e.g., [], (), ->, =) due to C++ semantics.</p></li><li class="list__item" id="jg8lqw_915"><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="jg8lqw_916"><p>If unary operator (eg. ++), implement as member.</p></li><li class="list__item" id="jg8lqw_917"><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="jg8lqw_918"><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="jg8lqw_906"><ol class="list _decimal" id="jg8lqw_919" type="1"><li class="list__item" id="jg8lqw_920"><p>Always think about const-ness of parameters.</p></li><li class="list__item" id="jg8lqw_921"><p>Return reference to support chaining << calls.</p></li><li class="list__item" id="jg8lqw_922"><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="jg8lqw_907"><span id="jg8lqw_923"><font style="color:#cd5c5c">Examples</font></span></p><p id="jg8lqw_908"><span id="jg8lqw_924"><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="jg8lqw_910"><span id="jg8lqw_925"><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="jg8lqw_912"><p id="jg8lqw_926">Declare non-member functions as friends of a class to give them access to private members.</p></aside></section><section class="chapter"><h4 id="11-3-principle-of-least-astonishment-pola" data-toc="11-3-principle-of-least-astonishment-pola">11.3 Principle of Least Astonishment (POLA)</h4><p id="jg8lqw_927"><span id="jg8lqw_929"><font style="color:#8a2be2">From the C++ Core Guidelines (section C ):</font></span></p><ul class="list _bullet" id="jg8lqw_928"><li class="list__item" id="jg8lqw_930"><p id="jg8lqw_934">Design operators primarily to mimic conventional usage.</p></li><li class="list__item" id="jg8lqw_931"><p id="jg8lqw_935">Use nonmember functions for symmetric operators.</p></li><li class="list__item" id="jg8lqw_932"><p id="jg8lqw_936">Use nonmember functions for symmetric operators.</p><ul class="list _bullet" id="jg8lqw_937"><li class="list__item" id="jg8lqw_938"><p id="jg8lqw_943">Compound operators return reference to *this</p></li><li class="list__item" id="jg8lqw_939"><p id="jg8lqw_944">Arithmetic operators return copies</p></li><li class="list__item" id="jg8lqw_940"><p id="jg8lqw_945">In/decrement prefix vs. postfix rules</p></li><li class="list__item" id="jg8lqw_941"><p id="jg8lqw_946">Indexing requires const and non-const versions</p></li><li class="list__item" id="jg8lqw_942"><p id="jg8lqw_947">Look at the C++ reference for common patterns!</p></li></ul></li><li class="list__item" id="jg8lqw_933"><p>Always provide all out of a set of related operators.</p></li></ul></section><section class="chapter"><h4 id="11-4-interesting-operators" data-toc="11-4-interesting-operators">11.4 Interesting Operators</h4><p id="jg8lqw_948"><span id="jg8lqw_952"><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="jg8lqw_950"><span id="jg8lqw_953"><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="12-special-member-functions" data-toc="12-special-member-functions">12 Special Member Functions</h3><p id="jg8lqw_954"><span id="jg8lqw_965"><font style="color:#8a2be2">Six types of special member functions:</font></span></p><p id="jg8lqw_955">Every class has them by default.</p><p id="jg8lqw_956">These functions are generated only when they're called (and before any are explicitly defined by you):</p><ul class="list _bullet" id="jg8lqw_957"><li class="list__item" id="jg8lqw_966"><p id="jg8lqw_972"><span id="jg8lqw_973"><font style="color:#ff00ff">Default constructor:</font></span> Takes no parameters and creates a new object.</p></li><li class="list__item" id="jg8lqw_967"><p id="jg8lqw_974"><span id="jg8lqw_975"><font style="color:#ff00ff">Destructor:</font></span> Called when an object goes out of scope.</p></li><li class="list__item" id="jg8lqw_968"><p id="jg8lqw_976"><span id="jg8lqw_977"><font style="color:#ff00ff">Copy constructor:</font></span> Creates a <span id="jg8lqw_978"><u>new object</u></span> as a member-wise copy of another.</p></li><li class="list__item" id="jg8lqw_969"><p id="jg8lqw_979"><span id="jg8lqw_980"><font style="color:#ff00ff">Copy assignment operator:</font></span> Assigns an <span id="jg8lqw_981"><u>already existing object</u></span> to another.</p></li><li class="list__item" id="jg8lqw_970"><p id="jg8lqw_982">Move constructor</p></li><li class="list__item" id="jg8lqw_971"><p id="jg8lqw_983">Move assignment operator</p></li></ul><p id="jg8lqw_958"><span id="jg8lqw_984"><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="jg8lqw_960"><p id="jg8lqw_985">About the return value:</p><ol class="list _decimal" id="jg8lqw_986" type="1"><li class="list__item" id="jg8lqw_987"><p id="jg8lqw_989"><span id="jg8lqw_990"><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="jg8lqw_988"><p id="jg8lqw_991"><span id="jg8lqw_992"><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="12-1-copy-constructor-copy-assignment-operator" data-toc="12-1-copy-constructor-copy-assignment-operator">12.1 Copy Constructor & Copy Assignment Operator</h4><p id="jg8lqw_993">By default, the copy constructor will create copies of each member variable.</p><p id="jg8lqw_994"><span id="jg8lqw_1002"><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="jg8lqw_996"><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="jg8lqw_997"><p id="jg8lqw_1003">When the vectors go out of scope, their destructor tries to free the array.</p></aside><p id="jg8lqw_998"><span id="jg8lqw_1004"><font style="color:#8a2be2">Copy constructor:</font></span></p><ul class="list _bullet" id="jg8lqw_999"><li class="list__item" id="jg8lqw_1005"><p id="jg8lqw_1007">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="jg8lqw_1006"><p id="jg8lqw_1008">Deep copy all members where assignment does not work. e.g., pointers to heap memory.</p></li></ul><p id="jg8lqw_1000"><span id="jg8lqw_1009"><font style="color:#8a2be2">Copy assignment operator:</font></span></p><ul class="list _bullet" id="jg8lqw_1001"><li class="list__item" id="jg8lqw_1010"><p id="jg8lqw_1013">Clean up any resources in the existing object about to be overwritten.</p></li><li class="list__item" id="jg8lqw_1011"><p id="jg8lqw_1014">Copy members using initializer list when assignment works.</p></li><li class="list__item" id="jg8lqw_1012"><p id="jg8lqw_1015">Deep copy members where assignment does not work.</p></li></ul></section><section class="chapter"><h4 id="12-2-delete-operations" data-toc="12-2-delete-operations">12.2 Delete Operations</h4><p id="jg8lqw_1016">Setting a special member function to delete removes its functionality.</p><p id="jg8lqw_1017">We can also keep the default copy constructor if we declare other constructors.</p><p id="jg8lqw_1018"><span id="jg8lqw_1020"><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="12-3-rule-of-zero-three" data-toc="12-3-rule-of-zero-three">12.3 Rule of Zero/Three</h4><p id="jg8lqw_1021"><span id="jg8lqw_1026"><font style="color:#8a2be2">Rule of Zero:</font></span> If the default operations work, don't define your own custom ones!</p><p id="jg8lqw_1022">When the default one generated by the compiler does not work, you need to write your own special member functions.</p><p id="jg8lqw_1023">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="jg8lqw_1024"><span id="jg8lqw_1027"><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="jg8lqw_1025"><p id="jg8lqw_1028">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="12-4-copy-elision-and-return-value-optimization-rvo" data-toc="12-4-copy-elision-and-return-value-optimization-rvo">12.4 Copy Elision and Return Value Optimization (RVO)</h4><p id="jg8lqw_1029"><span id="jg8lqw_1032"><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="jg8lqw_1031"><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="13-move-semantics" data-toc="13-move-semantics">13 Move Semantics</h3><section class="chapter"><h4 id="13-1-lvalues-rvalues" data-toc="13-1-lvalues-rvalues">13.1 lvalues & rvalues</h4><p id="jg8lqw_1035"><span id="jg8lqw_1043"><font style="color:#8a2be2">Definitions</font></span></p><ul class="list _bullet" id="jg8lqw_1036"><li class="list__item" id="jg8lqw_1044"><p id="jg8lqw_1046"><span id="jg8lqw_1047"><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="jg8lqw_1045"><p id="jg8lqw_1048"><span id="jg8lqw_1049"><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="jg8lqw_1037"><thead><tr class="ijRowHead" id="jg8lqw_1050"><th id="jg8lqw_1056"></th><th id="jg8lqw_1057"><p>l-value</p></th><th id="jg8lqw_1058"><p>r-value</p></th></tr></thead><tbody><tr id="jg8lqw_1051"><th id="jg8lqw_1059"><p>Find address using address-of operator (&var)</p></th><td id="jg8lqw_1060"><p>Yes</p></td><td id="jg8lqw_1061"><p>No</p></td></tr><tr id="jg8lqw_1052"><th id="jg8lqw_1062"><p>Intuitive Definition</p></th><td id="jg8lqw_1063"><p>Can appear either left or right of an assignment *</p></td><td id="jg8lqw_1064"><p>Can appear only on the right of an assignment *</p></td></tr><tr id="jg8lqw_1053"><th id="jg8lqw_1065"><p>Lifetime</p></th><td id="jg8lqw_1066"><p>Decided by scope</p></td><td id="jg8lqw_1067"><p>Ends on the very next line (unless you purposely extend it!)</p></td></tr><tr id="jg8lqw_1054"><th id="jg8lqw_1068" rowspan="2"><p>Value References</p></th><td id="jg8lqw_1069"><p id="jg8lqw_1071">An <span id="jg8lqw_1073"><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="jg8lqw_1070"><p id="jg8lqw_1074">An <span id="jg8lqw_1076"><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="jg8lqw_1055"><th id="jg8lqw_1077" colspan="2"><p id="jg8lqw_1078">A <span id="jg8lqw_1080"><font style="color:#dda0dd">const</font></span> <span id="jg8lqw_1081"><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="jg8lqw_1038"><p id="jg8lqw_1082">*: This was technically the definition until 2011. Technically there are these weird things called gl-values, pr-values, x-values, ...</p></aside><p id="jg8lqw_1039"><span id="jg8lqw_1083"><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="jg8lqw_1041"><p id="jg8lqw_1084">An r-value reference is an alias to an r-value</p><p id="jg8lqw_1085">BUT the r-value reference itself is an l-value</p></aside><figure id="jg8lqw_1042"><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="13-2-move-semantics" data-toc="13-2-move-semantics">13.2 Move Semantics</h4></section></section><section class="chapter"><h3 id="inheritance" data-toc="inheritance">14 Inheritance</h3><section class="chapter"><h4 id="14-1-namespace" data-toc="14-1-namespace">14.1 Namespace</h4><p id="jg8lqw_1089"><span id="jg8lqw_1094"><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="jg8lqw_1090"><span id="jg8lqw_1095"><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="jg8lqw_1091"><p id="jg8lqw_1096">Here is an analogy from Wikipedia:</p><p id="jg8lqw_1097">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="jg8lqw_1092"><span id="jg8lqw_1098"><font style="color:#8a2be2">Most modern languages use namespaces to fix this.</font></span></p><div class="tabs" id="jg8lqw_1093" 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="14-2-overriding-and-overloading" data-toc="14-2-overriding-and-overloading">14.2 Overriding and Overloading</h4><p id="jg8lqw_1107"><span id="jg8lqw_1117"><font style="color:#8a2be2">Definition:</font></span></p><ul class="list _bullet" id="jg8lqw_1108"><li class="list__item" id="jg8lqw_1118"><p id="jg8lqw_1120"><span id="jg8lqw_1121"><font style="color:#ff8c00">Overloading</font></span>: Methods with the same name but different signature.</p></li><li class="list__item" id="jg8lqw_1119"><p id="jg8lqw_1122"><span id="jg8lqw_1123"><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="jg8lqw_1109"><p id="jg8lqw_1124">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="jg8lqw_1111"><p id="jg8lqw_1125">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="jg8lqw_1113"><p id="jg8lqw_1126">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!");
}
}