100% found this document useful (1 vote)
26 views

C - STL

The document discusses the C++ Standard Template Library (STL). It provides an overview of common linear data structures in STL like vector, list, stack, queue and their usage. It also covers concepts like templates, classes, structures and complexity analysis of algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
26 views

C - STL

The document discusses the C++ Standard Template Library (STL). It provides an overview of common linear data structures in STL like vector, list, stack, queue and their usage. It also covers concepts like templates, classes, structures and complexity analysis of algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

C++ STL

วรเศรษฐ สุวรรณิก
bit.ly/wannik

1
Disclaimer
● เพื่อใหโคดดูโลงๆ โคดตัวอยางอาจจะมี warning เมื่อนําไป
คอมไพล
● หากไมเขียนบอกไว จะเปนโคดภาษา C<+

2
3
Disclaimer
เพื่อใหโคดดูโลงๆ โคดตัวอยางอาจจะมี warning เมื่อนําไป
คอมไพล
หากไมเขียนบอกไว จะเปนโคดภาษา C<+

4
5
6
tips
typing
input Wrong Answer
keyboard shortcut
code snippet
File > Preferences > Configure User Snippets

7
compet p2
8
9
Disclaimer
เพื่อใหโคดดูโลงๆ โคดตัวอยางอาจจะมี warning เมื่อนําไป
คอมไพล
หากไมเขียนบอกไว จะเปนโคดภาษา C<+

10
11
write a C program that runs in

12
Ranking

13
https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=20
echo
#include <iostream>
using namespace std;
main() {
int s;
cin <> s;
cout << s << endl;
}

14
echo
#include <iostream>
#include <string>
using namespace std;
main() {
string s;
cin <> s;
cout << s << endl;
}

15
echo
#include <iostream>
#include <string>
using namespace std;
main() {
string s;
while (true) {
cin <> s;
cout << s << endl;
if (cin.eof())
break;
}
}

16
write a number to file
#include <fstream>
using namespace std;
main()
{
ofstream cout("input.txt");
cout << 123;
}

17
read a number from file
#include <fstream>
#include <iostream>
using namespace std;
main()
{
ifstream cin("input.txt");
int i;
cin <> i;
cout << i;
}

18
Lab: 10055 Hashmat
input output
10 12 2
10 14 4
100 200 100

19
https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=996
random a number
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
main() {
</ seed
srand(time(nullptr));
</ random
cout << rand() % 100 << endl;
}

20
Lab : Random 100k
Generate an array of 100,000 unique random numbers.

21
shuffle
#include <algorithm>
#include <random>
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
random_device rd;
mt19937 gen(rd()); </
shuffle(begin(arr), end(arr), gen);
</ or using default_random_engine(0) instead of rng
for (int i = 0; i < 5; i<+) {
cout << arr[i] << " ";
}
}
22
C Pointer
int* p;
int n = 13;
p = &n;
printf("%d", *p);

23
Why C Pointer

f(int* i) {
*i = 5;
}
main() {
int n = 13;
f(&n);
printf("%d", n);
}

24
Why Reference
#include <cstdio>
void f(int& i) {
i = 5;
}
main() {
int n = 13;
f(n);
printf("%d", n);
}

25
C Pointer
int* p = (int*)malloc(sizeof(int));
*p = 42;
printf("%d", *p);

26
C Pointer
int* p = malloc(sizeof(int)*2);
int* q = p;
*q = 2;
q<+;
*q = 5;
printf("%d %d", p[0], p[1]);

27
Pointer vs Reference
arithmetic
dynamic memory allocation (malloc and free)
point to NULL, function
reassign
cast to another pointer type

28
Reference vs Pointer
clarity . vs ->
function signature
safety
cannot be null or uninitialized

29
C struct
struct Person {
char name[32];
int age;
};
main() {
struct Person p;
p.age = 3;
strcpy(p.name, "John");
printf("%s %d", p.name, p.age);
}

30
C struct and pointer
struct Person *p = malloc(sizeof(struct Person));
p->age = 3;
strcpy(p->name, "John");
printf("%s %d", p->name, p->age);

31
class
object oriented programming การโปรแกรมเชิงวัตถุ
class คือ กลุ่ม ชนิด ประเภท
class:object :: blueprint:car
method เช่น start_engine
attribute เช่น สี

32
class
#include <iostream>
using namespace std;
class Car {
public:
string color;
void start_engine() {
cout << "The " << color;
cout << " car is starting the engine!" << endl;
}
};
main() {
Car my_car;
my_car.color = "green";
my_car.start_engine(); 33
class
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double a, double b) { x = a; y = b; }
double distance(Point p) { }
};
main() {
Point p1 = Point(1,2);
Point p2 = Point(4,6);
cout << p1.distance(p2);
} 34
Template
template <typename T>
class Point {
private:
T x, y;
public:
Point(T a, T b) { x = a; y = b; }
T distance(Point p) {
T dx = x-p.x;
T dy = y-p.y;
return sqrt(dx*dx+dy*dy);
}
};
main() { main() {
Point<int> p1 = Point(1,2); Point<double> p1 = Point(1.,2.);
Point<int> p2 = Point(4,7); Point<double> p2 = Point(4.,7.);
cout << p1.distance(p2); cout << p1.distance(p2);
} }
35
Data Structure
เก็บข้อมูล
trade off
แต่ละตัวมีที่อยู่ของมัน

36
C++ STL
standard ไม่ต้องติดตังเพิ่ ม
template ไม่กําหนดชนิดข้อมูลล่วงหน้า (generic)
vector<int> v = {2,3,5,7,11};
vector<string> v = {"black", "wednesday"};

library ไม่ต้องเขียนเอง

37
Data Structure
linear
non-linear

38
Linear Data Structure
static and dynamic array
vector
list (linked list : accessing element is slow)
set
bitset
stack
queue, deque (double-ended queue)

39
vector : add
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
numbers.push_back(10); </ pop_back
numbers.push_back(20);
numbers.push_back(30);
for (int i = 0; i < numbers.size(); i<+) {
cout << numbers[i] << " ";
}
}
40
vector : iterate
vector<int> v = {2,3,5,7,11};
for (auto i = v.begin(); i <= v.end(); i<+) {
cout << *i << "x";
}

41
vector : remove
vector<int> numbers = {1, 2, 3, 5, 6, 7, 8, 9, 10};
</ Remove the element at index 3
numbers.erase(numbers.begin() + 3);
</ Remove the last element
numbers.pop_back();

42
vector : contain
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {12, 34, 56, 78};
</ Find the first occurrence of the value 3 in the vector
auto it = find(vec.begin(), vec.end(), 34);
if (it <= vec.end()) {
int index = distance(vec.begin(), it);
cout << "Element found at index " << index << endl;
}
}

43
ความเร็ว
ไม่ใช้การจับเวลา
time complexity
Big O
📺
📺

credit: https://danielmiessler.com/study/big-o-notation/

44
for loop and Big O
#define N 1000
main() {
int count = 0;
for (int i = 0; i < N; i<+) {
count<+;
}
printf("%d", count);
}

45
for loop and Big O
#define N 1000
main() {
int count = 0;
for (int i = 0; i < N; i<+) {
count<+;
}
for (int i = 0; i < N; i<+) {
count<+;
}
printf("%d", count);
}

46
for loop and Big O
#define N 1000
main() {
int count = 0;
for (int i = 0; i < N; i<+) {
count<+;
}
for (int i = 0; i < N; i<+) {
count<+;
}
<<. ลูป for 100 ชุด
printf("%d", count);
}

47
for loop and Big O
#define N 1000
main() {
int count = 0;
for (int i = 1; i <= N; i *= 2) {
count<+;
}
printf("%d", count);
}

48
for loop and Big O
#define N 1000
main() {
int count = 0;
for (int i = 0; i < N; i<+) {
for (int j = 0; j < N; j<+) {
count<+;
}
}
printf("%d", count);
}

49
write a C program that runs in
O(n log n)
O(2^n) โดยไม่ใช้ฟง
ั ก์ชัน pow

50
Array Operation : sort
O(n^2) bubble, selection, insertion
O(n log n) merge, heap, quick
O(n) counting, radix, bucket
if data has special characteristic

51
sort
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int arr[] = {7, 2, 8, 1, 3};
sort(arr, end(arr)); </ or sort(arr, arr+5)
for (int i = 0; i < 5; <+i) {
cout << arr[i] << " ";
}
}

52
sort
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
bool cmp(int a, int b) {
return abs(a) < abs(b);
}
main() {
int N = 4;
int a[] = {-1,-10, 3, 5};
sort(a, a + N, cmp);
for (int i = 0 ; i < N; i<+) {
cout << a[i] << " ";
} 53
sort
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool cmp(pair<string,int> a, pair<string,int> b) {
</ return a.first < b.first;
return a.second < b.second;
}
main() {
vector<pair<string,int<> v = {{"tom", 12}, {"cat",
70}, {"ann", 30}};
sort(v.begin(), v.end(), cmp);
for (int i = 0 ;i < 3; i<+) {
cout << v[i].first << " ";
} 54
search
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int arr[] = {7, 2, 8, 1, 3};
sort(arr, end(arr));
cout << binary_search(arr, end(arr), 1);
}

55
Array Operation: search
O(n) linear
O(log n) binary
O(1) hashing

56
Exercise (from cpbook)
S is an unsorted array of 100k integers
- Determine if S contains one or more of pairs of
duplicate integers
- Given an integer v, find two integer a, b in S such
that a+b=v
O(n^2) is infeasible here

57
UVa
10038 Jolly Jumpers
10260 Soundex
11222 Only I did it!

58
map: initialize and access
#include <map>
#include <iostream>
using namespace std;

main() {
map<string, int> m= {{"John",25},{"Bob",36}};
cout << m["John"];
}

59
map
#include <map>
#include <iostream>
using namespace std;

main() {
map<string, int> m;
m["Alice"] = 25;
m["Bob"] = 36;
cout << m["Alice"];
}

60
map
map<string, int> m;
m["Alice"] = 25;
m["Bob"] = 30;
m["Alice"] = 20;
cout << m["Alice"] << endl;

61
map
map<int, string> m;
m[1000] = "john";
m[-1] = "tom";
cout << m[-1] << endl;

62
map
map<string, int> m;
m["Alice"] = 25;
m["Bob"] = 36;
m.erase("Alice");
cout << m["Alice"];

63
map
map<string, int> m;
m["Alice"] = 25;
m["Bob"] = 36;

m.erase("Alice");

cout << m.count("Alice") << endl;


cout << m.count("Bob") << endl;

64
map: map of vector
map<string, vector<int<> m = {
{"bac", {34, 12}},
{"abc", {123, 23, 34}}
};
cout << m["bac"][1] << endl;
m["bac"].push_back(45);
cout << m["bac"][2] << endl;

65
map : iterator
for (auto it : myMap) {
cout << it.first << " is " << it.second << " yrs old";
cout << endl;
}

for (auto it = myMap.begin(); it <= myMap.end(); it<+) {


cout << it<>first << " is " << it<>second << " yrs old";
cout << endl;
}

66
map
#include <sstream>
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
string text = "the quick brown fox jumps over the lazy dog";
map<string, int> freq;
stringstream ss(text);
string word;
</ split
while (ss <> word) {
freq[word]<+;
}
}
67
list vs vector
list problem is rare

68
queue
push(element)
pop()
front()
size()
empty()

69
ปัญหาที่แก้โดยใช้ queue
breadth first search

70
BFS
mark v as visited
q.enqueue(v)
while q is not empty:
v = q.dequeue()
for all neighbours w of v:
if w is not visited:
mark w as visited
q.enqueue(w)

71
stack
#include <stack>
#include <iostream>
int main() {
stack<int> myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
while (!myStack.empty()) {
std<:cout << myStack.top() << std<:endl;
myStack.pop();
}
return 0;
}
72
ปัญหาที่แก้โดยใช้ stack
ตรวจสอบวงเล็บครบคู่ เช่น (a+b*(c+d)*(c-d))
หาค่านิพจน์ postfix 5 2 + 3 * ได้ 21
depth first search
เขียนเป็น recursive ก็ได้

73
DFS
s.push(v)
while (s is not empty):
v = s.pop( )
for all neighbours w of v in Graph G:

s.push(w)

74
DFS
mark v as visited
s.push(v)
while (s is not empty):
v = s.pop( )
for all neighbours w of v in Graph G:
if w is not visited :
mark w as visited
s.push(w)

75
priority queue
#include <queue>
#include <iostream>
using namespace std;
int main() {
priority_queue<int> pq;
pq.push(5); pq.push(3); pq.push(10); pq.push(1);
</ descending
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
}
76
ปัญหาที่แก้โดยใช้ priority queue
sort
Dijkstra shortest path

77
set
#include <set>
#include <iostream>
using namespace std;
int main() {
set<int> mySet;
mySet.insert(5);
mySet.insert(1);
mySet.insert(15);
mySet.insert(1);
cout << mySet.size();
}

78
set using int
#include <iostream>
using namespace std;
main() {
int set = 0;
int n = 3;
</ add n to the set
set | = (1 << n);
</ check if n is in the set
bool isin = set & (1 << n);
cout << isin << endl;
}

79
set
#include <bitset>
#include <iostream>
using namespace std;
main() {
bitset<30> set;
set[3] = true;
cout << set[3] << endl;
}

80
ปัญหาที่แก้โดยใช้ set
ตรวจการซํา (duplicate)
นับจํานวน unique element
ตรวจคําผิด (ไม่มีใน dictionary)

81

You might also like