0% found this document useful (0 votes)
18 views

C++ Notes

Uploaded by

2305038
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

C++ Notes

Uploaded by

2305038
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Changing file streams:

Flushing Buffer:
Time:

See also ratio<> template and class instantiations

time_t t = time(NULL)

struct tm gmt = *gmtime(&t)

struct tm localt = *localtime(&t)


len = strftime(buf, bufSize, "%Y-%m-%d %H:%M:%S %Z", &localt);
rand() generates random numbers between 0 and RAND_MAX. srand(time_t) sows the seed for Implementing function pointers:
generating different random numbers at different time. Generaaly srand(time(NULL)) used. rand() %
len gives any random number between 0 and len
Using system(char * ) we can give commands in a C/C++ program that will be directly run in the
terminal.
Falling Matrix:
Vectors: vector<string>v1, v1 = {…}, v1(“Helmp”), v(10), vi2(ia, ia + size), v(10, “Value”)  size 10 & initial value “Value”
.size(), .front(), .back(), .begin(), .end(), .insert(it , “Ok”), .erase(it), .push_back(“Lelz”), .pop_back(), .find (it1, it2, “Yes”) .resize(num) .clear()
Vectors, lists and strings have powerful pointers called iterators : vector<int>::iterator it, that support +=, -+, ++, –, *
Iterators are input, output, forward, bidirectional and random access. Vectors and strings support all. Lists support bidirectional, sets support input and output
.end() returns iterator past the last element.
Concatenate two vectors: vector1.insert( vector1.end(), vector2.begin(), vector2.end() )
Vectors can also be used as an array like vi[8].

List: list<int> li, li = {…}, li(1, 2, 2) , li(ia, ia + size)


We can use all the members and functions of a vector using lists except for random access ( li[5] not allowed ).
In lists we can use and .push_back() .pop_front() method

Pairs: pair<int, string>p, p(42, “Hemlo”), p = {1, 2}


.first, .second, make_pair<int, string>(43, “Bye”)
There are 2 elements (any more will throw an error)

Tuple: tuple<string, string, string> t2, t2(“One”, “Two”, “Three”), t2 = {1, 2, 3}


get<0>(t1), get<1>(t1), make_tuple<int, int, int>(3, 4, 5) tie(a, b, c) = t2  takes the values of t2 and stores them into a, b, c;
No of elements must match with no of bases. Note: Here std::ignore is frequently used to keep a box empty
Tuples are like variable pairs.

Sets and multisets: set<string> strset, strset = {…}  cannot have duplicate, multiset<string> strset, strset = {…} can have duplicate
.size(), .insert(“Value”)  this returns pair<set<string>::iterator, bool>, .find(“Helmp”)  returns iterator to found if found, else returns an iterator to end, .erase(it)
.erase(“Value”) .begin() .end() tie(a, b, c) = strset .count(“Value”)  in sets returns 1 or 0 .lower_bound(“Value”) .upper_bound(“Value”)
We cannot random access in a set which makes sense because they all remain sorted. They are like dictionaries
There is also unordered_set<> and unordered_multiset<> that uses hashes, while sets and multisets uses balanced binary tree

Maps: map<string, string> my_map, my_map = {{George, Father}, {Evelyn, Mother}} mutimap<string, string> my_dict = {{..},{..},…}
.find(“George”)  returns an iterator to the pair, .first, .second, .begin(), .end(), .size(), .insert({ "Luke", "Neighbor" })
my_map[“George”]  will not work for mutimaps, .count(“George”)
Maps are like sets of pairs (sorted w.r.t the first index). They are used for hashes: map<int, vector<string>>
There are also unordered_map;
Queue (FIFO): queue<int, list<int>> ql(li), queue<string> qd  deque
.size() .front() .empty() .pop() .push("one") .back()
and Stack (LIFO):
.size() .top() .empty() .pop() .push("one")

Priority queue  by default maxheap: priority_queue<int> gquiz priority_queue<int, vector<int>, greater<int>> gquiz, pq(arr, arr + size)minheaps
.size() .top() .empty() .pop() .push(1) .swap(gpquiz)

Strings:
.size() .length() .front() .back() .begin() .end() .rbegin() .resize(num) .insert(it, ‘X’) .erase(it) .push_back(‘S’)
.replace(pos from front, no of char, new substr) .substr(pos from front, no of char) .substr(pos from front) .find(‘s’) .rfind(‘s’)
.find_first_of(‘S’) .npos .append(str) .compare(str)

Algorithms: (inline funcs mean function pointers, function operators (functors) and lambda functions)
*max_element (first_iterator, last_iterator) *min_element (first_iterator, last_iterator) accumulate(first_iterator, last_iterator, initial value of sum)
count(first_iterator, last_iterator, x) find(first_iterator, last_iterator, x) binary_search(first_iterator, last_iterator, x) lower_bound(first_iterator, last_iterator, x)
upper_bound(first_iterator, last_iterator, x) distance(first_iterator, desired_position) search(haystack it1, haystack it2, needle it1, needle it2)
equal(start it, middle it, end it) count_if(start it, end it, inline funcs) .erase(unique(arr.begin(),arr.end()),arr.end()) sort(first_iterator, last_iterator)
reverse(first_iterator, last_iterator) next_permutation(first_iterator, last_iterator) prev_permutation(first_iterator, last_iterator) for_each(it1, it2, inline funcs)
transform(main it1, main it2, store it, inline funcs) random_shuffle(first it, last it) equal_range(first_iterator, last_iterator, x)
distance(first_iterator, last_iterator), to_string(number)
move(b.begin(), b.end(), std::back_inserter(a)) copy(b.begin(), b.end(), std::back_inserter(a))
void qsort (void* array, size_t array_size, size_t size_of_element, int (*comparator) (const void*,const void*));
Policy Based Data Structures: indexed_set s
.insert(“Value”) .find_by_order(pos) .order_of_key(“Value”)
Must: #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds;
This is like a set that supports random access

bitset<N>: bset1, bset2(20), bset3(string("1100")), set8​


As bitset stores the same information in compressed manner. N must be known at compile time​
Allows random access like set8[4] = 1​ ; Comparison, bitwise, left/right shift assignment operators can also be used.​
.count() .size() .test(i) .any() .set() / .set(4,0) / .set(4) .reset() / .reset(2) .flip() / .flip(2) bitset<8>num ​
>MACROS: Macros are generally used in header files to declare many constants, vars and funcs
#define func (params) {…} #define PI 3.141592
Example: #define MAX (a , b) { (a) > (b) ? (a) : (b) }
Use line continuation ( \ ) for multiple lines
There are other macro conditionals like: #ifdef #ifndef #elif #else #endif
Example: To prevent the same header file being include twice, we wrap the header file in an “include guard”:
#ifndef _INCLUDE_A
#define _INCLUDE_A

#endif

>LAMBDA FUNCTIONS: [capture_declaration] (parameters) -> return_type {…}


Example: [&] (int c) -> char {…}

>FUNCTION POINTERS: Note: return_type and parameters must be same for fptr and func
return_type (*fptr) ( parameters ) = func | use: var = (*fptr)( parameters ) [ Example: void (*x) ( ) = func; ]
return_type (*fptr[ ]) ( parameters ) = {a , b, c, d, e, NULL} | use: var = fptr[i] ( params ) [ Example: void (*x[ ]) ( ) = {a , b, c, d, e, NULL}; ]
vector< return_type (*) () > fptr = {a , b, c, d, e} } | use: var = fptr[i] ( params ) ) [ Example: vector< int (*) ( ) > x = {a , b, c, d, e }; ]

>FUNCTORS (function objects): return_type and parametes = of the function;


class funcName {
class_vars;
public:
funcName ( #some_param ); // Constructor
return_type operator ( ) ( parameters ) { …. }
};
Use:
1. Make a object of funcName: funcName func_obj ( #some_params ); var = func_obj ( parameters )
2. In many algorithms, where inline funcs can be used: funcName ( #some_param ) is used, which creates a temporary object with constructor argument. The parameter for the function call
is given by the algorithm from the range of iterators it points to. Example: sort(arr, arr+n, greater<int>()), sort(arr, arr+n, comparator)
>TEMPLATES: “Type” is a type agnostic parameter
Template functions: template < typename Type > return_type funcName ( parameters ) { … }
CPP REGEX SYNTAX

Regex ref: https://regexr.com/


Regex vis: https://www.debuggex.com/
regex tutorial:
https://www.youtube.com/watch?v=sa-TUpSx1JA
CPP regex: https://www.youtube.com/watch?v=9K4N6MO_R1Y

python regex:
https://www.youtube.com/watch?v=K8L6KVGG-7o

You might also like