Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
3295 lines (2512 loc) · 98.9 KB
/
Copy pathmain.cpp
File metadata and controls
3295 lines (2512 loc) · 98.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
C++ cheatsheat.
Features which are identical to C will not be described.
*/
/*
# Linux specifics
The main c++ lib on linux is the GNU Standard C++ Library.
Shared object name: `libstdc++.so`.
Website: <http://gcc.gnu.org/libstdc++/>
Get source code: seems to be on the same tree as gcc?
git clone git://gcc.gnu.org/git/gcc.git
- the so is usually located at
/usr/lib/i386-linux-gnu/libstdc++.so.X
If it is not there then
locate libstdc++
- std headers are usually located at
/usr/include/c++/4.X/`.
If not, try:
locate /iostream
- the Ubuntu package is called `libstdc++6.X`. `dpkg -l | grep libstd`
With `g++` the C++ standard library is linked against automatically.
This does not happen when compiling with `gcc`, and is one of the many reasons why you should use `g++`
whenever compiling C++ instead of `gcc`.
*/
#include "common.hpp"
class Class {};
// struct
template<class T>
struct BaseStruct {
T i;
BaseStruct(T i) : i(i) {}
protected:
int iProtected;
private:
int iPrivate;
};
struct DerivedStruct : BaseStruct<int> {
DerivedStruct(int i) : BaseStruct(i) {
iProtected = i;
}
};
// # global scope
int global = 0;
// Differently from C, expressions can be evaluated to initialize globals.
int global2 = global + 1;
int ret1() {
callStack.push_back("before main!");
return 1;
}
int global3 = ret1();
// ERROR: only single expressions that initialize a global are allowed however.
//global = 1;
//if (1){}
//callStack.push_back("global");
// #preprocessor
// The C++ preprocessor it Turing complete by mistake.
//
// This leads to the concept of Template Metaprogramming,
// which allows you to write code that is ultra DRY / runs fast but is very large.
// TODO confirm.
// string
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
//File IO
void ios_write_fail(std::string path) {
throw std::ios_base::failure("Error: Could not write to file: " + path);
}
void ios_read_fail(std::string path) {
throw std::ios_base::failure("Error: Could not read file: " + path);
}
/**
Read entire file into a string at once.
*/
void read_file(std::ifstream &ifs, std::string &data_read) {
ifs.seekg(0, std::ios::end);
size_t size = ifs.tellg();
data_read.resize(size);
ifs.seekg(0);
ifs.read(&data_read[0], size);
ifs.close();
}
//to_str
template <class K, class V>
std::string map_to_str(std::map<K,V> map) {
std::stringstream result;
for (auto& pair : map) {
result << pair.first << ":" << pair.second << ", ";
}
return result.str();
}
// Attributes.
void noreturn_func [[ noreturn ]] () { throw 1; }
// Misc
bool odd(int i){ return (i % 2) == 1; }
/*
# main
# main signature
- http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main
- http://stackoverflow.com/questions/1621574/can-the-arguments-of-mains-signature-in-c-have-the-unsiged-and-const-qualifie
Much like in C, only:
int main();
int main(int, char*[]);
are required to work, but more likely work as well.
# Call main from the program
In C++, cannot be called from anywherelse in the program, including recursively:
http://stackoverflow.com/questions/2128321/can-main-function-call-itself-in-c
This restriction does not seem to exist in C.
*/
int main() {
// # Scope
{
/*
# typedef struct
# typedef class
# struct keyword omission
Unlike in C, struct tags and variable names live in the same namespace.
In C++ you can normally omit `struct`
`struct s` is called an #elaborated-type-specifier.
http://stackoverflow.com/a/14261176/895245
But if there is ambiguity, the only way to refer to the struct
is by appending `struct`.
*/
{
int s = 1;
struct s {int i;};
assert(s == 1);
// ERROR
//s t = {1};
struct s t = {1};
assert(t.i == 1);
int c = 1;
class c { public: int i; };
assert(c == 1);
// ERROR
//c u = {1};
class c u = {1};
assert(u.i == 1);
}
}
/*
# assign operator
Unlike in C, C++ assign operator returns lvalues!
TODO rationale. Related to return refs from functions?
*/
{
int i = 0, j = 1, k = 2;
(i = j) = k;
/*^^^^^^^^^
|
returns a lvalue pointing to `i`
Therefore is the same as:
i = j;
i = k;
*/
assert(i == 2);
assert(j == 1);
assert(k == 2);
// ERROR: as in C, most other operators do not return lvalues
//(i + j) = k;
}
/*
# constant expressions at compile time
http://en.cppreference.com/w/cpp/language/constant_expression
Constant expressions at compile time can be used in contexts where non constants cannont:
- array lengths at array declaration
- numeric template parameters
The compiler is able to determine which expressions are constant recursively.
Note that variables with the keyword `const` may or may not be constant expressions.
depending on how they are initialized.
Those defined with the keyword constexpr however are ensured by the compiler to be
compile time constants.
*/
/*
Get array length, find array length: <http://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array>
Besides the C sizeof method which does not work for pointers and has lots of duplication, C++ offers:
*/
{
// Vector class. Has overhead, but probably the best option given its flexibility.
// #array class. No overhead. Fixed size. Template based.
{
// WARN: double brackets required TODO why
//std::array<int, 3> a{0, 1, 2};
std::array<int, 3> a{{0, 1, 2}};
assert(a.size() == 3);
}
// Method which I don't understand.
{
//template<class T, size_t N>
//size_t size(T (&)[N]) { return N; }
}
}
/*
# array size from variables
In C++, any constant expression at compile time can be used as an array size.
This includes in particular intetegers declared as `const` and initialized by a constant expression,
and in C++11 all `constexpr` variables.
*/
{
std::srand(time(NULL));
{
int i = 1;
i = std::rand();
// ERROR: the size would not be fixed
//int is[i];
}
{
// Compile time constant since the literal 1 is a constant expression.
const int ci = 1;
// Cannot do that, so the size is fixed!
//ci = 2;
int is[ci];
}
// ERROR: the compiler is able to see that ci is not a compile time constant
{
const int ci = std::rand();
//int is[ci];
}
}
/*
# vla
called variable length array VLS
C99 supports this
compiler implementation:
must increment/decrement stack pointer at each array
meaning, one extra multiplication and sum for every VLA declared
*/
{
{
//cin >> i;
//int is4[i];
}
{
// ERROR: may not be initialized
//cin >> i;
//int is4[i] = {1, 2};
}
}
// # enum
{
// Unlike C, already does typedef, no need to write enum all the time.
{
enum E {A, B, C};
E e = A;
}
#if __cplusplus >= 201103L
// Set storage size.
{
enum E : char {A, B, C};
assert(sizeof(E) == sizeof(char));
}
#endif
}
// # for
{
//you can define i inside the for scope only
int is[] = {0, 1, 2};
for (int i=0; i<3; i++)
{
assert(i == is[i]);
// ERROR: already declared in this scope
//int i;
}
}
#if __cplusplus >= 201103L
#endif
/*
# struct
Structs in C++ are very similar to classes: support access modifiers,
inheritance, constructors, templates, etc.
The major difference between them is that the default access modifier for structs
is public, while for classes it is private.
This is why structs are used on many simple short language examples:
no public line is needed.
The Google C++ style guide recommends using struct only if there is no constructors,
and classes otherwise.
<http://stackoverflow.com/questions/2750270/c-c-struct-vs-class>
*/
{
struct DerivedStruct s(1);
assert(s.i == 1);
}
/*
# RTTI
Run time type information.
Any function that gets class information explicitly at runtime:
- `typeid`
- `dynamic_cast`
Google style 3.26 discourages this, since if you really need it your design is probably flawed.
Also using typeid on variables means that extra meta data must be kept about those variables.
*/
/*
# typeid
Get type of variables.
Can be done for both types and variables of the type.
Returns objects of `type_info`
# type_info
Type returned by `typeid`.
*/
{
/*
typeid returns `type_info`.
However copy and assign for type_info are private,
so the following fails.
*/
{
//std::type_info t = typeid(int);
//std::type_info t(typeid(int));
}
// type_info implements `==` and `!=`.
//
// typeid's of different types are always different.
{
int i, i1;
int& ia = i;
Class c;
assert(typeid(i) == typeid(int) );
assert(typeid(ia) == typeid(int&));
assert(typeid(i) == typeid(i1) );
assert(typeid(i) != typeid(c) );
}
/*
`name`: return a string representation of the type.
The exact string is implementation defined.
`name()` is implementation defined.
On GCC, you can demangle with `__cxa_demangle`:
http://stackoverflow.com/questions/4465872/why-typeid-name-returns-weird-characters-using-gcc
*/
{
std::cout << "typeid(int).name() = " << typeid(int).name() << std::endl;
}
// before: <http://stackoverflow.com/questions/8682582/what-is-type-infobefore-useful-for>
// hash_code: return a size_t hash of the type
}
/*
# type_index
Wrapper around type_info that allows copy and assign.
*/
{
std::type_index t = typeid(int);
}
/*
# type_traits
<http://www.cplusplus.com/reference/type_traits/>
*/
{
}
// # stdlib
//
// # Standard library
{
// # string
{
// Initialize from string literal.
{
std::string s = "abc";
}
// cout works as expected.
{
std::string s = "abc";
std::stringstream oss;
oss << s;
assert(oss.str() == "abc");
}
/*
# + for strings
# cat
# concatenate.
Creates a new string.
The only way to do inline this without creating a new string seems to be by using stringstream.
http://stackoverflow.com/questions/662918/how-do-i-concatenate-multiple-c-strings-on-one-line
*/
{
std::string s = "ab";
std::string s1 = "cd";
assert(s + s1 == "abcd");
assert(s + "cd" == "abcd");
assert("cd" + s == "cdab");
}
// length
{
std::string s = "abc";
assert(s.length() == 3);
}
{
std::string s = "abc";
s[0] = 'A';
assert(s == "Abc");
// BAD: no born check! Compiles.
//s[3] = 'd';
}
/*
# lowercase
http://stackoverflow.com/questions/313970/stl-string-to-lower-case
*/
{
// Best stdlib way with transform:
std::string s = "AbCd1_";
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
assert(s == "abcd1_");
//Boost has a single function: boost::algorithm::to_lower(str);
}
/*
# c_str
Convert std::string to C null terminated char* string.
*/
{
std::string s = "abc";
assert((std::strcmp(s.c_str(), "abc")) == 0);
}
// # substring
{
std::string s = "abcde";
assert(s.substr(1, 3) == "bcd");
}
// # Split at a character into array of strings.
{
// Best stdlib solution for any character: http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c
// There are shorters sstream solutions that split at whitespace.
// For Boost it's a one liner.
{
assert((split("01:23::45", ':') == std::vector<std::string>{"01", "23", "", "45"}));
std::vector<std::string> v;
split("01:23::45", ':', v);
assert((v == std::vector<std::string>{"01", "23", "", "45"}));
}
}
/*
# strip
# chomp
# trim
Exact same techniques as removing elements from vectors but for characters.
It's just that those operations are so common on strings...
http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
*/
{
// A single character: remove and erase idiom.
// Single remove_all call in Boost.
{
std::string s = "a bc d";
auto end = s.end();
s.erase(std::remove(s.begin(), end, ' '), end);
assert((s == "abcd"));
}
// Any character in a string: remove_if + custom function. std::ispunct is a typical choice.
// Single liner with boost::remove_if + is_any_of.
{
std::string s = "a,bc. d";
auto end = s.end();
// stdc ispunct:
s.erase(std::remove_if(s.begin(), end, ::ispunct), end);
// stdlib ispunct. Fails without the cast.
//s.erase(std::remove_if(s.begin(), end, (int(*)(int))std::ispunct), end);
assert((s == "abc d"));
}
}
/*
# getline
Read istream until a any given character, by default newline, and store chars read into a string.
The other major method of getting data from streams is `operator<<`,
which generaly speaking reads until whitespace. getline is generaly saner.
Returns the stream itself, which allows to:
- chain calls
- do while(getline) combos, as streams can be converted to bool via the `void*()`
operator which returns a pointer type which is then converted to a boolean.
*/
{
// Up to newline.
{
std::stringstream ss;
std::string s;
ss << "ab\n\nc";
// The delim is removed from the string.
assert(std::getline(ss, s));
assert(s == "ab");
// Empty
assert(std::getline(ss, s));
assert(s == "");
// No problem if end of stream.
assert(std::getline(ss, s));
assert(s == "c");
// Stream over.
assert(!std::getline(ss, s));
}
// The stream itself is returned.
{
std::stringstream ss;
std::string s;
std::string s2;
ss << "ab\n\nc";
std::getline(std::getline(ss, s), s2);
assert(s == "ab");
assert(s2 == "");
}
// Up to custom char.
{
std::stringstream ss;
std::string s;
ss << "ab::f";
std::getline(ss, s, ':');
assert(s == "ab");
}
// Read stream line-wise.
{
std::stringstream ss;
std::string line;
std::vector<std::string> lines;
ss << "ab\n\nc";
while (getline(ss, line))
lines.push_back(line);
assert((lines == std::vector<std::string>{"ab", "", "c"}));
}
}
/*
# stringstream
# basic_stringstream
An iostream String backed implementation.
The following is defined:
typedef basic_stringstream<char> stringstream;
typedef basic_stringstream<char>
Very useful to test streams without creating files / stdin.
*/
{
std::stringstream oss("abcd");
// str does not clear the std::stringstream object
assert(oss.str() == "abcd");
// To clear it you could do: http://stackoverflow.com/questions/20731/in-c-how-do-you-clear-a-stringstream-variable
// Set to empty:
oss.str("");
// Clear flags. Very important, not only for error indicators but also for end of stream.
oss.clear();
assert(oss.str() == "");
// ERROR: use of deleted function because the constructor is =delete.
//oss = std::stringstream();
}
// Possible application: build up a huge string step by step.
// May be more efficient than concatenations which always generates new objects.
{
std::stringstream oss;
oss << "ab";
oss << "cd";
assert(oss.str() == "abcd");
}
/*
# int to string
There are a few standard alternatives.
<http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c>
*/
{
/*
C++11 solves the question once and for all with a robust one-liner for base types.
It is not intended however for class input.
*/
#if __cplusplus >= 201103L
assert(std::to_string(123) == "123");
#endif
/*
std::stringstream seems to be the best pre C++11 solution.
It also has the advantage of working for any class that implements `operator<<`.
*/
{
std::stringstream oss;
oss << 123;
assert(oss.str() == "123");
}
/*
C sprintf
Works, but uses too many conversion operations.
*/
{
char cs[16];
std::sprintf(cs, "%d", 123);
std::string s = (cs);
assert(s == "123");
}
}
// #int to string
// http://stackoverflow.com/questions/7663709/convert-string-to-int-c
{
// Best C++11 error checking option: stoi
#if __cplusplus >= 201103L
assert(std::stoi("123") == 123);
#endif
}
}
/*
# io
See cppref now: http://en.cppreference.com/w/cpp/io
Take a good look at the inheritance tree.
The following are defined:
extern istream cin; //standard input (stdin)
extern wistream wcin;
extern ostream cout; //standard output (stdout)
extern wostream wcout;
extern ostream cerr; //standard error (stderr)
extern wostream wcerr;
extern ostream clog; //standard log (stdlog)
extern wostream wclog;
# istream #ostream
Istream and ostream are IO interfaces.
They have many implementations, backed by different types of data:
- files
- strings in memory
The main methods of getting data out of streams are:
- getline for linewise operations
- operator << for word wise operations
- read(char*, size_t). Reads a fixed number of characters into an array.
# endl
System dependent newline.
*/
{
/*
# cout
stdout.
`ostream` object.
For tests, std::stringstream shall be used as the results can then be tested,
and the behaviour is identical to cout.
`<<` is very magic. You need to understand:
- operator overload
- function template argument deduction
- namespaces adl
before really understanding why it works.
# cerr
Cout for stderr
# clog
By default also points to stderr, but can be redirected with TODO.
*/
{
std::cout << "cout" << std::endl;
std::cerr << "cerr" << std::endl;
std::clog << "clog" << std::endl;
}
/*
# cin #stdin
`istream` object.
Avoid using it for similar reasons as scanf:
- hard to handle invalid inputs
- difficult to predict behaviour
getline is the best option.
*/
{
//std::cout << "Enter an integer:" << endl;
//std::cin >> i;
//std::cout << i << std::endl;
}
// This is how a very explicit usage of `<<` would look like
{
std::stringstream ss;
//TODO0 how to get his working?
//std::operator<<<std::ostream,std::string>(ss, "explicit");
std::operator<<(std::operator<<(ss, "explicit "), "call");
}
// #<< left shift overload
{
}
// #>> right shift overload istream
// Get input out of streams into string.
// Overloaded for many different types of inputs: <http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/>
{
// char*, std::string
// - skip whitespace as defined by `isspace`.
// - read until first whitespace found
{
std::stringstream ss("ab cd\tef \t\ngh i.;)j");
std::string s;
ss >> s;
assert(s == "ab");
ss >> s;
assert(s == "cd");
ss >> s;
assert(s == "ef");
ss >> s;
assert(s == "gh");
ss >> s;
assert(s == "i.;)j");
}
// Numeric types: int, float.
// - skip whitespace as defined by `isspace`.
// - read until cannot be part of the type anymore (TODO what does that mean exactly?)
{
std::stringstream ss("1.0 2 \n \t 3.0f 4a a");
float f;
std::string s;
ss >> f;
assert(f == 1.0f);
ss >> f;
assert(f == 2.0f);
ss >> f;
assert(f == 3.0f);
// f suffix is not part of floats
ss >> s;
assert(s == "f");
ss >> f;
// TODO what happens? Error checking.
}
// Since `>>` returns the istream, it is possible to chain calls:
{
std::stringstream ss("1 1.5 2");
int i, j;
float f;
ss >> i >> f >> j;
assert(i == 1);
assert(f == 1.5);
assert(j == 2);
}
}
/*
# printf format strings
In C++ there is no more printf formatting strings: must use the C libs for that.
It is possible however to obtain some level of formatting control with manipulators.
# manipulators
Allow to control the output format.
*/
{
/*
# boolalpha
Control the format of boolean printing.
- on: print `true` or `false`
- no: print `1` or `0` (default)
Mnemonic: if true use alpha chars. Else, use numeric chars.
*/
{
std::stringstream ss;
ss << std::boolalpha << true;
assert(ss.str() == "true");
ss.str("");
ss << std::noboolalpha << true;
assert(ss.str() == "1");
ss.str("");
//default is noboolalpha
ss << true;
assert(ss.str() == "1");
ss.str("");
}
/*
Once an options is eaten by the ostream, it stays as the default option.
*/
{
std::stringstream ss;
ss << std::boolalpha;
ss << true;
assert(ss.str() == "true");
ss.str("");
//does not clear earlier passed options
ss << true;
assert(ss.str() == "true");
ss.str("");
ss << std::noboolalpha;