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

C and C++ titbits

The document contains various code snippets demonstrating the use of structures, strings, threads, atomic operations, queues, vectors, sets, priority queues, and maps in C++. It illustrates the implementation of function pointers, string manipulation methods, producer-consumer patterns with threads, and operations on data structures like vectors and maps. Additionally, it includes examples of binary representation and arithmetic operations.

Uploaded by

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

C and C++ titbits

The document contains various code snippets demonstrating the use of structures, strings, threads, atomic operations, queues, vectors, sets, priority queues, and maps in C++. It illustrates the implementation of function pointers, string manipulation methods, producer-consumer patterns with threads, and operations on data structures like vectors and maps. Additionally, it includes examples of binary representation and arithmetic operations.

Uploaded by

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

Function Pointer

struct point

int x;

int y;

void (*print)(const struct point*);

};

void print_x(const struct point* p) {

printf("x=%d\n", p->x);

void print_y(const struct point* p) {

printf("y=%d\n", p->y);

int main(void) {

struct point p1 = { 2, 4, print_x };

struct point p2 = { 7, 1, print_y };

p1.print(&p1);

p2.print(&p2);

String

Modifiers:

operator+=Append to string (public member function)

push_back Append character to string (public member function)

assign Assign content to string (public member function)

insert Insert into string (public member function)


erase Erase characters from string (public member function)

replace Replace portion of string (public member function)

swap Swap string values (public member function)

pop_back

int main ()

{ std::string str="We think in generalities, but we live in details.";

std::string str2 = str.substr (3,5); // "think" std::size_t pos = str.find("live"); //


position of "live" in str std::string

str3 = str.substr (pos); // get from "live" to the end

std::cout << str2 << ' ' << str3 << '\n'; return 0;

Thread

std::queue<int> dataq;

pthread_mutex_t m1;

pthread_mutexattr_t attr;

void* producer(void* arg)

while(1)

for(int i = 0; i < 10; i++)

pthread_mutex_trylock(&m1);

dataq.push(i);
pthread_mutex_unlock(&m1);

void* consumer(void* arg)

while(!dataq.empty())

pthread_mutex_trylock(&m1);

dataq.pop();

pthread_mutex_unlock(&m1);

int main() {

pthread_t pid1;

pthread_t pid2;

pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);

pthread_mutex_init(&m1, &attr);

pthread_create(&pid1, NULL, &producer, NULL);

pthread_create(&pid2, NULL, &consumer, NULL);

sleep(1);

pthread_exit(NULL);

pthread_exit(NULL);

return 0;
}

#include <stdio.h>

#include <stdbool.h>

#include <stdatomic.h>

atomic_flag f = ATOMIC_FLAG_INIT;

int main(void)

bool r = atomic_flag_test_and_set(&f);

printf("Value was: %d\n", r); // 0

r = atomic_flag_test_and_set(&f);

printf("Value was: %d\n", r); // 1

atomic_flag_clear(&f);

r = atomic_flag_test_and_set(&f);

printf("Value was: %d\n", r); // 0

Queue

empty

Test whether container is empty (public member function)

size

Return size (public member function)


front

Access next element (public member function)

back

Access last element (public member function)

push

Insert element (public member function)

emplace

Construct and insert element (public member function)

pop

Remove next element (public member function)

swap

Swap contents (public member function)

Make vector from set and vice versa

vector<TreeNode*> v(s1.begin(), s1.end());

unordered_set<TreeNode *> s(v.begin(), v.end());

// Create a vector vector<int> v; /

/ Assigning all elements of set into vector // using std::vector::assign()


method v.assign(s.begin(), s.end());

Vector – > Erase from index 1 to index 3

v.erase(v.begin()+1, v.begin()+3)

v.erase(v.end()-1) //erase last index

v.erase(v.begin()) //erase first index


Vector initialize -

vector<type> v(n, val); 1-D

vector<vector<int>> out(n, vector<int>(n, 0)); 2-D

Set --> Erase

// Define the range to erase second to fifth elements

auto first = next(st.begin(), 1);

auto last = next(st.begin(), 5);

// Remove all elements in the range [first, last)

st.erase(first, last);

Priority_Queue

priority_queue<pair<int, int>, vector<pair<int, int>>,


decltype(&comparator)> pq(comparator);

bool comparator(pair<int, int> a, pair<int, int> b)

if(abs(a.first - a.second) < abs(b.first - b.second))

return true;

return false;

stable_sort(s.begin(), s.end(), comp);

set<pair<int, int>, decltype(&comp)> s(comp);


Map :: erase

// insert some values:

mymap['a']=10;

mymap['b']=20;

mymap['c']=30;

it=mymap.find('b');

mymap.erase (it); // erasing by iterator

mymap.erase ('c'); // erasing by key

it=mymap.find ('e');

mymap.erase ( it, mymap.end() ); // erasing by range

// Iterator to the second element

auto it = next(mp.begin(), 1);

// Remove the element

mp.erase(it);

N in binary

cout << n << " in binary is " << bitset<32>(n) << endl;

cout << n << " in binary is " << bitset<32>(n) << endl;

To find modulo division of a power of 2

Num&((pow of 2) - 1)
Eg 5%2 = 1

101&1 = 1

5%8 = 5

101&111 = 5

Find mininum of 2 numbers

minimum(x, y) = y + ((x - y) & ((x - y) >> 31)).

Maximum of 2 numbers

x - ((x - y) & ((x - y) >> 31))

Multiply 2 numbers

Let the two given numbers be 'a' and 'b'

1) Initialize result 'res' as 0.

2) Do following while 'b' is greater than 0

a) If 'b' is odd, add 'a' to 'res'

b) Double 'a' and halve 'b'

3) Return 'res'.

You might also like