C++ Programming: Compile, Debug, and Basics
C++ Programming: Compile, Debug, and Basics
1
• Eg: enum months {JAN =1, FEB, APR=4,MAY}; Continue continue: Continue next iteration.
Here, MAY is 5.
5. Control Flow Works for while, for, do while
If switch is within a loop and if continue is
used inside switch and if it is executed, then
4. Arithemetic and logical operation the loop skips to next loop.
– expr1,expr2 Do While do
Use sparingly, Eg: i++,j-- statement
while (expression );
– x = (Conditional expresion)? expr1 : expr2
x =expr1 if Conditional expression is true, else x = Break break : Exit the the loop or control.
expr2. Works for while, for, do while and switch
2
6. Functions 7. Pointers and arrays 7.6. Arrays and pointers
The following two are equivalent:
6.1. int main function: command line argu- 7.1. Pointers pa = &a[0]; pa = a;
ments Declaration type *ptr ;
a[i] *(a + i)
p[i] *(p + i)
main(int argc, char *argv[]) Eg: int *p; f(int arr[]) f(int *arr)
{ Initialization type *ptr = val ;
Legal Illegal
··· Eg: int *p = 0;
} Eg: int *p = NULL;// Null pointer. pa++ a++
argc Number of arguments including the program Eg: int *p = (int *) 100; pa[-1] a[-1]
name. NOTE: Casting is required for integer other than
argv[0] Pointer to program name. zero. Also, the above memory location may not be
7.7. Pointer to functions
NOTE: argv[0] represents name of the available. Eg:
compiled program and not the source file & Gives address. int sum f(int size, int arr[], int (*foo)(int )) // Definition.
and how it is called eg: [Link] vs ./[Link] Eg: ptr = &x; {
argv[i] Pointer to ith argument. * Dereferencing operator. int sum = 0;
argv[argc - 1] Pointer to last argument. Eg, *ptr refers to x. for (int i = 0; i < size; i++)
sum += (*foo)(arr[i]);
6.2. Function definition 7.2. Arrays }
Here foo is a pointer to a function and (*foo) is the function.
type function name (argument list ) • Character arrays sum f(size, arr, square) // [Link] of squares.
{ char s[100]; sum f(size, arr, cube) // [Link] of cubes.
statements s = "abc"; //ERROR. NOTE: Function names act as pointers to the function.
··· *s = "abc"; // OK.
return expression char s[] = {’a’,’b’,’c’};
} char s[] = "abc";
eg:
int foo(int num, int cars[],char *pn) • Integer, float arrays
{ int num[100]
statements num = {1,2,3} // ERROR
··· *num = {1,2,3} // ERROR
return expression int num[] = {1,2,3}
} float num[] = {1.0,2.0,3.0}
3
8. Structures, unions and typedefs 8.3. Union Using capture:
A union is a variable that may hold objects of different types and sizes. Lambda functions can also be stored in variables like the add in the
following example.
8.1. Structure The syntax is based on structures:
union u tag {
• Definition: int ival; #include <iostream>
struct point float fval;
{ char *sval; int main() {
int x; } u; int x = 10;
int y; For example, integer value of u can be accessed as: int y = 20;
}; [Link] auto add = [x, y]() -> int {
NOTE-1: Structure tag is optional?? return x + y;
NOTE-2: In C a function cannot be a member of a structure. 8.4. Bit fields int result = add();
Eg: };
• Declaration examples: }
struct {
unsigned int is keyword : 1;
– struct {· · · } a,b,c;
unsigned int is extern : 1;
unsigned int is static: 1;
– struct point {· · · } a,b,c;
} flags;
10. Bit operations
– struct point a,b,c This defines flags that contains three 1-bit fields.
The number following the colon represents the field width.
10.1. Builtin functions
– struct point *p; builtin clz Count leading zeros.
Namespace using namespace std;
With this statement standard library functions can be used without builtin ctz Count trailing zeros.
• Accessing members the prefix std:: builtin popcount Count number of ones.
a.x = 5; builtin parity Parity of number of ones.
printf("%d\n",a.x);
9. Lambda Functions Bit hacks
• Accessing members with pointer Format:
struct point *p = &a; [capture](parameters) -> return type {body}
The following are equivalent:
• Capture: Captures variable from the surrounding scope by
value or reference.
– p -> x;
Eg: [a,&b]
– (*p).x; • Parameters: Parameters of the function.
– a.x; Eg: (int a, int b)
Return type: Return type of the function.
• Arrays of structure:
struct points pts[100]; Examples
struct {· · · } pts[] = {{· · · },{· · · },· · · ,{· · · }}; Sorting in reverse order:
NOTE: In above assignment, in the RHS, elements within the
braces could be of different types matching the members of the sort([Link](), [Link](), [](int a, int b) -> bool {
structure. return a > b;
In case of simple members, each members need not be enclosed });
within braces.
Counting number of elements in a vector:
4
11. Input output 11.5. printf and scanf Printf and variants
• int printf(char *format, arg1, arg2, · · · );
11.1. File Access Conversion formats for printf and scanf Print output to stdout.
Character Argument type; Printed as
Format: • int sprintf(char *string, char *format arg1, arg2, · · · );
FILE *fp; d,i int; decimal number
Print output to string.
FILE *fopen(char *name, char *mode); o int; unsigned octal number (without leading zero)
x,X int: unsigned hexadecimal number (without a leading • int fprintf(FILE *fp, char *format arg1, arg2, · · · );
int fclose(FILE *fp);
0x or 0X), using abcdef or ABCDEF. Print output to file pointed by the file pointer fp.
fp = fopen(name, mode);
Allowable modes include: u int; unsigned decimal number. Example:
"r" read. zu size t. printf("%s\n", string var);
"w" write. c int; single character. printf("%s", "hello, world");
"a" append. s char *; Print string, scan word. printf("square of n is %d\n", n square);
"b" binary files: "rb", "wb", "ab". NOTE: scanf reads only a word and not the entire
NOTE: Difference between rb and r etc: string.
While using just "r" might work in writing binary files, it might cause f double; [-][Link]. Scanf and variants
trouble due misinterpretation of special characters like LF and CR. e,E double; [-][Link]±xx, or [-][Link]±xx. • int scanf(char *format, arg1, arg2, · · · );
See: [Link] g,G double; %e or %E if exponent is < -4 or >= precision, Scan input from stdin.
else use %f. • int sscanf(char *string, char *format arg1, arg2, · · · );
Standard I/O p void *; pointer. Scan input from string.
Can be treated in the same way as file pointer. % no argument; Print %.
Between % and conversion character there may be in order: • int fscanf(FILE *fp, char *format arg1, arg2, · · · );
stdin, stdout, stderr Scan input from the file pointed by the file pointer fp.
• Minus sign: Left justification.
11.2. Reading and writing a file NOTE1: unlike printf, in scanf the variable are pointers.
size_t fread{const void* ptr, size_t size,/ • Number: Minimum field width. NOTE2: In scanf %s reads a word and not the entire string.
size_t count, FILE* stream}; • Period: Separates field width from precision. Also see: [Link]
Examples:
• Number: Precision. scanf("%d", &n);
size_ t fwrite{const void* ptr, size_t size,/
For float: number of digits after decimal. sscanf(string, "%d", &n);
size_t count, FILE* stream};
For int: minimum number of digits. fscanf(fp, "%d", &n);
For string: maximum number of characters to be printed.
11.3. Character I/O
• h: for short integer. l: for long integer. 11.6. cin and cout
getchar Takes input from standard input.
int getchar() cin Read input until space, or tab or LF.
Equivalent to getc(stdin) Formatting rules cout Output.
putchar Output to standard output. Examples
Wildcard NOTE:
int putchar(int)
%*d Here precision can be specified dynamically. Eg: • Use the following to increase speed ot I/O.
Equivalent to putc(c), stdout
printf("%*d", 6, foo);, this is equivalent to ios_base::sync_with_stdio(false);
getc int getc(FILE *fp), Eg: getc(stdin)
printf("%6d",foo); [Link](nullptr); [Link](nullptr);
putc int putc(int c, FILE *fp)
Integers • Use [Link]() after cin and before using getline.
ungetc
%d print as decimal integer.
11.4. Line I/O %6d print as decimal integer, at least 6 characters wide.
gets Reads until EOF. Floating point numbers 11.7. Miscellaneous
gets deletes terminal \n %6f print as floating point. int fflush(FILE *stream)
puts Writes line to stdout. %.2f print as floating point, 2 characters after decimal Causes any buffered but unwritten data to be written. The effect is
puts adds terminal \n point. undefined on an input stream.
fgets char *fgets(char *line, int maxline, FILE *fp) %6.2f print as floating point, at least 6 characters wide and int fclose(FILE *stream)
fputs int *fputs(char *line, FILE *fp) 2 characters after decimal point. Flushes any unwritten data for stream, discardes any unread buffered
getline Eg: getline(cin, s). Where s is a string. String: example hello, world (12 chars). input.
:%s: :hello, world:
NOTE: Never use gets :%10s: :hello, world:
gets does not check for buffer overrun, and keeps reading until :%.10s: :hello, wor:
it encouters new line or EOF. It has been used to break computer :%-10s: :hello, world:
security. :%.15s: :hello, world:
:%-15s: :hello, world :
:%15 .10s: : hello, wor:
:%-15 .10s: :hello, wor :
5
12. Libraries String ¡-¿ numbers 12.5. Algorithms
Usually in Linux, the library header files are stored in /usr/include
String to numbers Sort and search
NOTE: Use #include <bits/stdc++.h> to include all standard Search and sort from C
libraries. From C library int atoi(char *s). • void *bsearch(const void *key, const void *base,
Variants: atof, atol, atod size t n, size t size,
12.1. Character class tests: <cctype> From C++ library int stoi(string s, size t *p = 0, int base int (*cmp) (const void *keyal, const void *datum))
= 10). Searches base[0] · · · base[n-1] for key.
isalpha(c) Comparison function must return negative if its first argument
Variants: stol, stod, stof, stold
isupper(c) (search key) is less than its second argument (a table entry)
Eg:
islower(c) and so on.
isdigit(c)
isalnum(c) • qsort(void *base, size t n, size t size,
int n = stoi("1234"); // n = 1234.
isspace(c) true for ASCII codes: 9-13 & 32. int (*cmp)(const *void, const *void))
int n = stoi("12", 0, 16); // n = 18.
toupper(c) int n = stoi("A", 0, 16); // n = 10. Search and sort from C++
tolower(c)
Compare functions:
Number to string bool compare(x, y){
12.2. String functions: <cstring> return(x strictly precedes y)
strcat(s,t) Concatenate t to end of s }
to string Eg: string s = to string(1234);\\s = ”1234”.
strncat(s,t,n)
strcmp(s,t) In all the below, a could be an iterator or a pointer and all of them
strncmp(s,t,n) can use custom compare functions.
strcpy(s,t) Copy t to s
Memory management
• y = lower bound(a, a+n, x)
strncpy(s,t,n) • void *calloc(size t nobj, size t size) Returns an iterator to the first element whose value is ≥ x.
strlen(s) Return pointer to array of nobj of size size.
The space is initialized to 0. • y = upper bound(a, a+n, x)
strchr(s,c) Return pointer to first c
Returns an iterator to the first element whose value is > x.
strchr(s,c) Return pointer to last c
• void *malloc(size t size) • y = equal range(a, a+n, x)
Returns pointer to an object of size size. Returns a pair of iterators pointing to the upper bound and
12.3. Mathematical function: <cmath> The space is uninitialized. lower bound of x.
sin(x) • void *realloc(void *p, size t size) • y = equal range(a, a+n, x, compare function)
asin(x) Change size of the object pointed to by p to size. Returns a pair of iterators pointing to the upper bound and
hsin(x) Return pointer to new space. lower bound of x.
exp(x)
• sort(it1, it2, compare function);
log(x) • free (void *p)
log10(x) Deallocates space point to by p. • stable sort(it1, it2, compare function);
pow(x,y) xy • is sorted(it1, it2, compare function);
sqrt(x) • is sorted until(it1, it2, compare function);
ceil(x) Memory management in C++ Returns the iterator to the element until which the array is
floor(x) sorted.
abs(x) Abs. val. of x. Returns integers types. • void* operator new(size)
Eg: myClass* p1 = new myClass; • find if(start it, end it, func)
fabs(x) Absolute value of x. Returns double
myClass* p1 = new(sizeof(myClass)); Returns iterator to the first element in the range [start it,
frexp frexp(int x, int *exp). Returns significand (y) in
end it) for which func returns true.
the range [0.5, 1) and the stores the exponent in exp, • void delete(void* ptr)
such that x = y ∗ eexp • find if not(start it, end it, func)
Eg: delete p1; delete(p1); Returns iterator to the first element in the range [start it,
ldexp ldexp(double y, int exp). Inverse of frexp.
modf double modf(x, double *ip). Splits x into integer end it) for which func returns false.
and fractional parts. Returns the fractional part and
stores integer parts at ip.
limits Min Max
fmod(x,y) Floating point remainder of x/y with the same sign as Examples: • max(a, b, comp); min(a, b, comp);
x. • max({a1, a2, a3}, comp); min({a1, a2, a3}, comp);
• numeric limits<int>::min()
• max element(a, a+n, comp);
12.4. Utility Functions: <cstdlib> • numeric limits<int>::max() Returns the iterator for the largest element in a. If there are
multiple largest element, returns the iterator/pointer for the
system(char *s) • numeric limits<double>::min() first one.
Run system commands.
Eg: system("date") • numeric limits<double>::infinity() • min element(a, a+n, comp);
6
Merge 13. Data structures 13.4. String
• merge(InputIterator F1, InputIterator L1, InputIterator A string is like a vector of characters.
F2, InputIterator L2, OutputIterator R); 13.1. Pair Definition:
Returns the iterator to the end of output. Eg: pair<int, int> x = 1,2; string s = "Hello";
NOTE: This operator does not allocate memory. The [Link] Returns 1. String operations:
OutputIterator R should point to a vector with sufficient [Link] Returns 2. a + b Concatenate.
memory to store the concatenated vector. [Link](t) append t to s.
• set intersection Arguments and output are the same as that 13.2. Tuple [Link](t) returns 0 if s == t, returns < 0 if s ≺ t,
for merge. Fixed length collection of heterogenous values. else returns > 0.
• set union Arguments and output are the same as that for Eg: tuple<int, string, double> t; [Link](start, len) Select a substring.
merge. Operations related to tuple [Link](str2) find first occurence of str2.
get<i> Return it h value of t. Eg: get<0>(t);. [Link](str2, pos) Find first occurence of str2 by searching
• set difference Arguments and output are the same as that for from the positon pos.
make tuple() Returns tuple out of individual values.
merge.
Eg: make tuple(5, "Paul", 23.4).
• set symmetric difference Arguments and output are the same tie() Unpacking tuple. 13.5. Set
as that for merge. Eg: Definition
tie(n, s, x) = t; set<type> s;
Hash Function tie(n, std::ignore, x) = t; multiset<type> s;
Can be used for custom types in unordered map and unordered set. unordered set<type> s;
13.3. Vectors unordered multiset<type, hasher> s;
Usage: hasher: Refer Custom Hash Function.
Definiton:
hash<T> hasher; Set operations
vector<T> v;
size t hasvalue = hasher(x);//Where x is an object of [Link](item);
Element access
type T operator[] [Link](item);
[Link]() Last element [Link](item);
[Link]() First element [Link](item); Returns the iterator that points to item.
Eg: Modifiers [Link]() Inserts elements in s.
[Link] back(5) Add 5 to the vector. Simillar to push in stack Eg: Insert elements from t to s.
hash<int> h; size_t x = h(10); data structure.
hash<string> h; size_t x = h("hello"); [Link]([Link](), [Link](), [Link]());
[Link]() Inserts elements / range in v. [Link]()
Custom hash function. Eg: Append u to v. Not availabe for unordered set and
Custom hash function for a user defined type can be defined as follows: [Link]([Link](), [Link](), [Link]()); unordered multiset.
[Link] [Link]{iterator pos, Args}. New element [Link] bound(x) Returns iterator to the smallest element that
class CustomHash { is constructed in place using Args and inserted
public: is larger than or equal to x.
at pos. [Link] bound(x) Returns iterator to the smallest element that
size_t operator () (const pair<string, string>& p) const { [Link] back [Link] back{Args}. New element is con-
hash<string> hasher; is larger than x.
structed in place using Args and inserted at the
auto h1 = hasher([Link]); NOTE: erase method remove all instances of the item in the multiset.
end.
auto h2 = hasher([Link]); IMPORTANT: Note the differences between
return h1 ^ h2; // Below for better heuristics. 13.6. Bit set
pushback, insert, emplace and emplaceback.
} [Link] back() Remove element on top of the stack. Definiton
}; [Link]() Remove element / range from v. bitset<size> s;
[Link]() Clears all the elements in v. Examples:
Heuristics to combine hash values.
Capacity bitset<5> s; bitset<5> s(string("1100110"));
h2 = h2 ^(h1 << 1); h2 ^= h2 + 0x9e3779b9 + (h1<<6) + (h1>>2);
[Link]() Returns the size of the vector. Operations on Bit set:
0x9e3779b9 is a prime number. a & b Bitwise AND.
See: [Link] [Link]() Current memory allocated to v in terms of
number of elements. a | b Bitwise OR.
[Link] size() Maximum memory available for v. a ^b Bitwise EXOR.
Others a Bitwise negation.
• swap(T& a, T&b); [Link]() Reserve a minimum size for v. Does not affect
[Link]().
• reverse(Iterator first, Iterator last); [Link] to fit() Shrink the capacity to fit the size.
13.7. Map
• next permutation([Link](), [Link]()); [Link]() Test if v is empty. map : Balanced binary tree.
• prev permutation([Link](), [Link]()); unordered map: Hash list.
tie Can be used to unpack a vector. Definition:
• random shuffle([Link](), [Link]()); Example: tie(a, b, c) = v; map<type1, type2> m;
Gives the next permutation for a given vector of integers. Eg: map<string, int> m;
unordered map<type1, type2, hasher> m;
7
hasher: Refer Custom Hash Function. 13.12. Priority queue
Operations on map Format:
m["banana"]
[Link]("banana")
Retrive value associated with banana.
Return 1 if the key is present else 0.
priority queue(type, vector<type>, compare) 14. Code snippets, etc.,
Max priority queue [Default]
[Link](); Eg: priority queue<int> q; 14.1. GCD:
Min priority queue
13.8. Stack priority queue<int, vector<int>, greater<int>> q; int gcd(int x, int y){
Eg: stack<int> s; [Link](3) return y ? gcd(y, x%y) : x;
[Link](5) [Link]() Returns the largest element. }
[Link]() [Link]() Removes the largest element.
[Link]()
Compare function for priority queues 14.2. Middle of an array
13.9. Queue class compare{ n: length of array
Eg: queue<int> q; public:
[Link](5) Adds element to the end. bool operator()(const T& x, const T& y) const {
return(x < y); // Max priority queue.
0-based indexing
[Link]() Removes first element. jnk
[Link]() Returns first element. // return(x > y); // Min priority queue. if n is odd:
[Link]() True if q is empty. } j2n k jnk
} if n is even: − 1 and
2 2
13.10. Dequeue
Eg: dequeue<int> d; 13.13. Iterators 1-based indexing
[Link] back(5) Add to the top. lnm
Iterators are like pointers but more specific to a collection. if n is odd:
[Link] front(2) Add to the bottom.
[Link] back() Remove from the top.
Not applicable for unordered set, unordered map and priority queue. l2n m lnm
if n is even: and +1
[Link] front() Remove from the bottom. 2 2
Example definition:
13.11. Heap vector<int>::iterator it; 14.3. Decimal to binary
set<string>::iterator it; int n;
Format:
Constructing a heap: cin >> n;
[Link]() Returns iterator pointing to the first element in the
auto a = bitset<64>(n);
make_heap(iterator f, iterator s); collection.
make_heap(iterator f, iterator s, comp); [Link]() Returns iterator pointing next to the last element in
the collection.
Iterating over a map: a[0] contains zeroth bit and so on.
pop_heap(iterator f, iterator s);
pop_heap(iterator f, iterator s, comp); Here *it is a pair of the key and value. Eg: pair<string, int> p =
*it;
push_heap(iterator f, iterator s); Eg:
push_heap(iterator f, iterator s, comp);
map<string, int>::iterator it = [Link]();
NOTE: // Accessing key and value
f points to the first element and s points next to the second element. string key = it->first;
f and s can be pointers when the heap is constructed over a array. int value = it->second;
Compare function:
Reverse Iterators
bool compare(x, y){
return(x < y); // For max heap 13.14. Representing graphs
return(x > y); // For min heap
} 13.15. Adjacency list
Eg:
vector<int> adj[N]// Unweighted graph.
vector<pair<int,int>> adj[N]// Weighted graph.
9
15.18. No code after return 16. Variable nomenclature for com-
Once I made the following mistake:
petitive programming
return [Link](); [Link]();
Using prefix
10
Eg: Description
na Number of elements in a
ma Map associated with a
sa Set associated with a
qa Queue or priority queue associated with a
ga Graph associated with a
11