4. Hello World in C
#include <stdio.h>
int main() {
printf("Hello, World!n");
return 0;
}
5. Hello World in C++
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
6. #include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
printf("Hello World againn");
return 0;
}
Dùng using namespace std để khai báo tập các hàm trong thư
viện chuẩn
printf hay nhiều hàm C vẫn có thể dùng lại trong C++
7. char name[] = "Steve Jobs";
cout << "Hello " << name << endl;
printf("Hello %sn", name);
int number;
scanf("%d", &number);
printf("Number is %dn", number);
cin >> number;
cout << "Number is " << number << endl;
Vào ra kết hợp cú pháp C và C++
8. #include <iostream>
#define NL endl;
using namespace std;
int main() {
cout << "Enter your choice" << NL;
cout << "N. Create new student record" << NL;
cout << "S. Search student by name" << NL;
cout << "E. Edit student record" << NL;
cout << "Q. Quit" << NL;
char c;
do {
cin >> c;
c = toupper(c);
switch (c) {
case 'N':
cout << "You select N" << NL;
break;
case 'S':
cout << "You select S" << NL;
break;
case 'E':
cout << "You select E" << NL;
break;
case 'Q':
cout << "You select Q to quit" << NL;
break;
}
} while (c != 'Q');
return 0;
}
cin không gặp lỗi như scanf
dính ký tự new line từ phía
trước
http://cpp.sh/95fjz
10. Cách học C++ nhanh nhất, hãy tham khảo
code ở đây
http://www.cplusplus.com
Và ở đây
http://cppreference.com
11. C String
• Terminated char 0
• <string.h> có nhiều hàm
xử lý chuỗi
• Rủi ro cao vì truy xuất
trực tiếp bộ nhớ
C++ String
• Class string gồm nhiều
method có tính đóng gói OOP
• Có thể chuyển đổi C string
sang C++ string và ngược
lại
12. string name = "Cuong";
cout << name << endl;
for (int i = 0; i < name.length(); i++) {
cout << name[i] << endl;
}
string fullName = "Trinh " + name;
cout << fullName;
char name[] = "Cuong";
for (int i =0; i < strlen(name); i++) {
printf("%cn", name[i]);
}
char fullName[200];
strcpy(fullName, "Trinh ");
strcat(fullName, "Cuong");
printf("%sn", fullName);
C++
C
13. char temp[] = "Hello"; //C string
string str2 = string(temp); //Khởi tạo C++ string từ C string
cout << str2 << endl;
const char* extract = str2.c_str(); //Trả về C string từ C++
cout << extract << endl;
str2.append(temp); //C++ string cộng với C string
str2 += temp; //Toán tử của C++ string chấp nhân C string
cout << str2 << endl;
http://cpp.sh/8h2me
20. C vs C++ array
• C chỉ có mảng kích thước cố định ngay
sau khi cấp phát
• C++ có:
– vector: dynamic size array
– array: fixed size array
– list: linked list
21. C array
• Kích thước mảng cố
định khi khởi tạo
• Có thể cấp phát
mảng trong vùng nhớ
heap
C++ vector
• Có thể thêm bớt phần
tử
• Dùng toán tử [] và
iterator để truy
xuất phần tử
• Có nhiều method hữu
dụng
22. vector<int> numbers = {1, 2, 3, 4};
for (auto i : numbers) {
cout << i << endl;
}
for (int i = 0; i < numbers.size(); i+= 2) {
cout << numbers[i] << endl;
}
numbers.push_back(5);
numbers.push_back(6);
numbers.push_back(7);
numbers.pop_back();
Dùng iterator
Dùng indexing
Thêm phần tử dễ dàng
23. vector<int> array = {1, 2, 3, 4};
array.push_back(5);
array.push_back(6);
array.push_back(7); //1,2,3,4,5,6,7
array.pop_back(); //1,2,3,4,5,6
auto begin = array.begin(); //begin = 1
begin += 3; //begin = 4
array.insert(begin, 1, 100); //1,2,3,100,4,5,6
auto end = array.end(); //
end -= 2; //5
array.insert(end, 1, 101); //1,2,3,100,4,101,5,6
24. #include <iostream>
#include <vector>
using namespace std;
int main () {
vector<int> arr = {1, 4, 2, 6, 3, 10, 9, 0};
sort(arr.begin(), arr.end());
for (auto i: arr) {
cout << i << " ";
}
//0 1 2 3 4 6 9 10
return 0;
}
Sắp xếp mảng C++
http://cpp.sh/2hqlpsort(arr.begin(), arr.end(), greater<int>());
Sắp xếp giảm dần
25. array<int, 6> fixArr = {1, 2, 3, 4};
for (auto i: fixArr) {
cout << i << " "; //1 2 3 4 0 0
}
vector
• Thêm bớt phần tử
cuối: push_back,
pop_back
• Chèn phần tử vào
giữa
array
• Mảng cố định
• Giống với mảng C
26. class Student {
public:
string name;
int age;
Student(string name, int age) {
this->name = name;
this->age = age;
}
};
vector<Student> students;
students.push_back(Student("Cuong", 10));
students.push_back(Student("Linh", 14)); http://cpp.sh/2vgkf
27. Hãy sắp xếp sinh viên theo tuổi
• Cách 1: viết hàm so sánh
• Cách 2: viết chồng toán tử so
sánh đối với class Student
http://cpp.sh/9kutz
28. • Dynamic array
• Operator []
vector list
• Linked List
• Không có []
29.
30. list<int> listInt = {1, 2, 3, 4};
listInt.push_back(5);
listInt.push_front(0);
auto iter = listInt.begin();
advance(iter, 2);
listInt.erase(iter);
// Erase all even numbers (C++11 and later)
for (auto it = listInt.begin(); it != listInt.end(); ) {
if (*it % 2 == 0) {
it = listInt.erase(it);
} else {
++it;
}
}
for (auto i: listInt) {
cout << i << " ";
} http://cpp.sh/7ahzb
31. Dồn chẵn sang trái, lẻ sang phải
• Use two indexes, left and right.
• Put left index at the start of array and right at the
end of the array.
• Increment left till odd number is not found.
• Decrement right till even number is not found.
• Swap left and right elements
• Do it till left<right
int arr[] = {1,2,3,4,6,8,7,12};
Output: [12, 2, 8, 4, 6, 3, 7, 1]
32. #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {9, 10, 1, 2, 3, 4, 6, 8, 7, 12};
auto left = arr.begin();
auto right = arr.end() - 1;
while (left < right) {
if (*left % 2 == 0) {
left++;
} else if (*right % 2 == 0) {
auto temp = *left;
*left = *right;
*right = temp;
}
if (*right % 2 == 1) {
right--;
}
}
for (auto i: arr) {
cout << i << " ";
}
return 0;
} http://cpp.sh/6w6vo
33. Kiểm thử C++ sử dụng catch.hpp
(ngoài lề một chút)
34. #define CATCH_CONFIG_MAIN /* This tells Catch to provide a main()
- only do this in one cpp file */
#include "catch.hpp"
unsigned int Factorial(unsigned int number) {
return number <= 1 ? number : Factorial(number - 1) * number;
}
TEST_CASE("Factorials are computed", "[factorial]"){
REQUIRE( Factorial(1)==1);
REQUIRE( Factorial(2) == 2);
REQUIRE( Factorial(3)== 6);
REQUIRE( Factorial(10)== 3628800);
}
https://github.com/philsquared/Catch
Chỉ cần copy file catch.hpp vào project
file này gồm cả header lẫn implementation nên
khá lớn
35. vector<int> separateOddEven(vector<int> arr) {
auto left = arr.begin();
auto right = arr.end() - 1;
while (left < right) {
if (*left % 2 == 0) {
left++;
} else if (*right % 2 == 0) {
auto temp = *left;
*left = *right;
*right = temp;
}
if (*right % 2 == 1) {
right--;
}
}
return arr;
}
Biến nó thành một hàm
có tham số vào và
kết quả trả về
36. #include <iostream>
#include <vector>
using namespace std;
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() -
only do this in one cpp file
#include "catch.hpp"
TEST_CASE("Separate Odd Event", "[separate]") {
REQUIRE(separateOddEven({1, 2}) == vector<int>({2, 1}));
REQUIRE(separateOddEven({1, 3, 2}) == vector<int>({2, 3, 1}));
REQUIRE(separateOddEven({9, 10, 1, 2, 3, 4, 6, 8, 7, 12}) ==
vector<int>({12, 10, 8, 2, 6, 4, 3, 1, 7, 9}));
}
Sử dụng catch
https://gist.github.com/TechMaster/fa5076be4feb8b02b4ede393e7eddf92
37. Hãy học thói quen viết kiểm thử
• Kiểm thử được (testable) giúp hàm:
– Có tham số vào ra rõ ràng
– Có chức năng cụ thể và cô đọng
– Phân tách module rõ hơn, không viết logic chi tiết
vào main
– Tái sử dụng tốt hơn
• Xây dựng bộ test case: đúng vs sai giúp lập
trình viên chuẩn bị cả những tình huống xấu