ݺߣ

ݺߣShare a Scribd company logo
Từ	C	đến	C++
Đơn giản mà đẹp
cuong@techmaster.vn
Khác biệt
• Vào ra console
• C string vs C++ string
• C array vs C++ vector, array, list
• Viết unit test
Vào ra console
Hello World in C
#include <stdio.h>
int main() {
printf("Hello, World!n");
return 0;
}
Hello World in C++
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
#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++
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++
#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
C string vs C++ string
Cách học C++ nhanh nhất, hãy tham khảo
code ở đây
http://www.cplusplus.com
Và ở đây
http://cppreference.com
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
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
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
string test = "Sex";
test += "y"; //Sexy
const char *str = test.c_str(); //Sexy
int pos = test.find("xy", 0); //2
test.substr(2, 2); //xy
test.append(3, 'Y'); //SexyYYY
test.erase(4, 10); //Sexy
http://en.cppreference.com/w/cpp/string/basic_string
http://cpp.sh/6nxf4
Đọc/ghi file
Ghi file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string fileName = "example.txt";
ofstream fileOut (fileName);
if (fileOut.is_open())
{
fileOut << "This is a line.n";
fileOut << "This is another
line.n";
fileOut.close();
} else {
cout << "Unable to open file";
}
return 0;
}
http://cpp.sh/7a6c
Đọc file
string line;
ifstream fileIn (fileName);
if (fileIn.is_open())
{
while (getline (fileIn,line) )
{
cout << line << 'n';
}
fileIn.close();
} else {
cout << "Unable to open file";
}
C++ vector: dynamic array
array: fixed array
C đến C++ phần 1
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
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
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
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
#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
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
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
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
• Dynamic array
• Operator []
vector list
• Linked List
• Không có []
C đến C++ phần 1
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
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]
#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
Kiểm thử C++ sử dụng catch.hpp
(ngoài lề một chút)
#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
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ó tàԳ một hàm
có tham số vào và
kết quả trả về
#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
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
Bài tập thực àԳ
Quản lý sinh viên
• Tạo class student
• Sử dụng vector để lưu trữ
• Sử dụng sort để sắp xếp

More Related Content

What's hot (20)

Phương pháp nhánh cận
Phương pháp nhánh cậnPhương pháp nhánh cận
Phương pháp nhánh cận
Diên Vĩ
đề Cương ôn thi lý thuyết chứng chỉ a tin học
đề Cương ôn thi lý thuyết chứng chỉ a tin họcđề Cương ôn thi lý thuyết chứng chỉ a tin học
đề Cương ôn thi lý thuyết chứng chỉ a tin học
Học Huỳnh Bá
Sổ tay thư viện hàm ngôn ngữ C
Sổ tay thư viện hàm ngôn ngữ CSổ tay thư viện hàm ngôn ngữ C
Sổ tay thư viện hàm ngôn ngữ C
vncoding
Bai tap excel
Bai tap excelBai tap excel
Bai tap excel
Hứa Tình
đồ áN xây dựng website bán laptop 1129155
đồ áN xây dựng website bán laptop 1129155đồ áN xây dựng website bán laptop 1129155
đồ áN xây dựng website bán laptop 1129155
nataliej4
Báo cáo đồ án cấu trúc dữ liệu đề tai49
Báo cáo đồ án cấu trúc dữ liệu đề tai49Báo cáo đồ án cấu trúc dữ liệu đề tai49
Báo cáo đồ án cấu trúc dữ liệu đề tai49
mydung09t3
Đề tài: Thiết kế Thùng rác thông minh, HAY, 9đ
Đề tài: Thiết kế Thùng rác thông minh, HAY, 9đĐề tài: Thiết kế Thùng rác thông minh, HAY, 9đ
Đề tài: Thiết kế Thùng rác thông minh, HAY, 9đ
Dịch vụ viết bài trọn gói ZALO 0917193864
Tim hieu thanh ghi in asm
Tim hieu thanh ghi in asmTim hieu thanh ghi in asm
Tim hieu thanh ghi in asm
My Đá
Đề thi Kỹ thuật lập trình có lời giải
Đề thi Kỹ thuật lập trình có lời giảiĐề thi Kỹ thuật lập trình có lời giải
Đề thi Kỹ thuật lập trình có lời giải
nataliej4
ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"
ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"
ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"
Tú Cao
Kiến trúc máy tính và hợp ngữ bài 02
Kiến trúc máy tính và hợp ngữ bài 02Kiến trúc máy tính và hợp ngữ bài 02
Kiến trúc máy tính và hợp ngữ bài 02
Nhóc Nhóc
Giáo trình c++ full tiếng việt
Giáo trình c++ full tiếng việtGiáo trình c++ full tiếng việt
Giáo trình c++ full tiếng việt
Môi Trường Việt
TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019
TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019
TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019
phamhieu56
56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh
56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh 56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh
56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh
Phước Nguyễn
ݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTT
ݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTTݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTT
ݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTT
Hiệu Nguyễn
Mảng 2 chiều
Mảng 2 chiềuMảng 2 chiều
Mảng 2 chiều
tienhien110293
ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...
ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...
ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...
nataliej4
Bien doi lapalce
Bien doi lapalceBien doi lapalce
Bien doi lapalce
Đức Hữu
Bo de toan roi rac (on thi cao hoc khmt)
Bo de toan roi rac (on thi cao hoc khmt)Bo de toan roi rac (on thi cao hoc khmt)
Bo de toan roi rac (on thi cao hoc khmt)
lieu_lamlam
Phương pháp nhánh cận
Phương pháp nhánh cậnPhương pháp nhánh cận
Phương pháp nhánh cận
Diên Vĩ
đề Cương ôn thi lý thuyết chứng chỉ a tin học
đề Cương ôn thi lý thuyết chứng chỉ a tin họcđề Cương ôn thi lý thuyết chứng chỉ a tin học
đề Cương ôn thi lý thuyết chứng chỉ a tin học
Học Huỳnh Bá
Sổ tay thư viện hàm ngôn ngữ C
Sổ tay thư viện hàm ngôn ngữ CSổ tay thư viện hàm ngôn ngữ C
Sổ tay thư viện hàm ngôn ngữ C
vncoding
đồ áN xây dựng website bán laptop 1129155
đồ áN xây dựng website bán laptop 1129155đồ áN xây dựng website bán laptop 1129155
đồ áN xây dựng website bán laptop 1129155
nataliej4
Báo cáo đồ án cấu trúc dữ liệu đề tai49
Báo cáo đồ án cấu trúc dữ liệu đề tai49Báo cáo đồ án cấu trúc dữ liệu đề tai49
Báo cáo đồ án cấu trúc dữ liệu đề tai49
mydung09t3
Tim hieu thanh ghi in asm
Tim hieu thanh ghi in asmTim hieu thanh ghi in asm
Tim hieu thanh ghi in asm
My Đá
Đề thi Kỹ thuật lập trình có lời giải
Đề thi Kỹ thuật lập trình có lời giảiĐề thi Kỹ thuật lập trình có lời giải
Đề thi Kỹ thuật lập trình có lời giải
nataliej4
ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"
ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"
ݺߣ báo cáo đồ án tốt nghiệp "Website cửa hàng điện thoại trực tuyến"
Tú Cao
Kiến trúc máy tính và hợp ngữ bài 02
Kiến trúc máy tính và hợp ngữ bài 02Kiến trúc máy tính và hợp ngữ bài 02
Kiến trúc máy tính và hợp ngữ bài 02
Nhóc Nhóc
TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019
TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019
TÀI LIỆU HƯỚNG DẪN THÍ NGHIỆM VẬT LÝ ĐẠI CƯƠNG ĐIỆN-TỪ VÀ QUANG_10294612052019
phamhieu56
56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh
56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh 56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh
56 câu hỏi tự luận và đáp án môn Tư tưởng Hồ Chí Minh
Phước Nguyễn
ݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTT
ݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTTݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTT
ݺߣ Báo Cáo Đồ Án Tốt Nghiệp CNTT
Hiệu Nguyễn
ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...
ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...
ĐỀ TÀI : ĐIỂM DANH BẰNG NHẬN DIỆN KHUÔN MẶT. Giảng viên : PGS.TS. HUỲNH CÔNG ...
nataliej4
Bo de toan roi rac (on thi cao hoc khmt)
Bo de toan roi rac (on thi cao hoc khmt)Bo de toan roi rac (on thi cao hoc khmt)
Bo de toan roi rac (on thi cao hoc khmt)
lieu_lamlam

Similar to C đến C++ phần 1 (20)

Stl vector nguyen_trihai_11520094_khmt06
Stl vector nguyen_trihai_11520094_khmt06Stl vector nguyen_trihai_11520094_khmt06
Stl vector nguyen_trihai_11520094_khmt06
Quach Long
Basic C programming
Basic C programmingBasic C programming
Basic C programming
TechMaster Vietnam
Lec3. Ham.pdf
Lec3. Ham.pdfLec3. Ham.pdf
Lec3. Ham.pdf
KinHongnh
C10 generic algorithms
C10 generic algorithmsC10 generic algorithms
C10 generic algorithms
Hồ Lợi
Nang cao c++
Nang cao c++Nang cao c++
Nang cao c++
Tiến Quang Phan
String c++
String c++String c++
String c++
ptquang160492
Chapter04_Array_chinhsua
Chapter04_Array_chinhsuaChapter04_Array_chinhsua
Chapter04_Array_chinhsua
ThnhNguynHong5
Control structure in C
Control structure in CControl structure in C
Control structure in C
TechMaster Vietnam
Àѳ屷ǰDz.
Àѳ屷ǰDz.Àѳ屷ǰDz.
Àѳ屷ǰDz.
Dorrissng

More from TechMaster Vietnam (20)

Neural Network from Scratch
Neural Network from ScratchNeural Network from Scratch
Neural Network from Scratch
TechMaster Vietnam
Go micro framework to build microservices
Go micro framework to build microservicesGo micro framework to build microservices
Go micro framework to build microservices
TechMaster Vietnam
Flutter vs React Native 2018
Flutter vs React Native 2018Flutter vs React Native 2018
Flutter vs React Native 2018
TechMaster Vietnam
Authentication and Authorization
Authentication and AuthorizationAuthentication and Authorization
Authentication and Authorization
TechMaster Vietnam
Postgresql security
Postgresql securityPostgresql security
Postgresql security
TechMaster Vietnam
Knex Postgresql Migration
Knex Postgresql MigrationKnex Postgresql Migration
Knex Postgresql Migration
TechMaster Vietnam
Postgresql các vấn đề thực tế
Postgresql các vấn đề thực tếPostgresql các vấn đề thực tế
Postgresql các vấn đề thực tế
TechMaster Vietnam
Arrowjs.io
Arrowjs.ioArrowjs.io
Arrowjs.io
TechMaster Vietnam
Minimum Viable Products
Minimum Viable ProductsMinimum Viable Products
Minimum Viable Products
TechMaster Vietnam
Chia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTTChia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTT
TechMaster Vietnam
Cơ sở dữ liệu postgres
Cơ sở dữ liệu postgresCơ sở dữ liệu postgres
Cơ sở dữ liệu postgres
TechMaster Vietnam
Node.js căn bản
Node.js căn bảnNode.js căn bản
Node.js căn bản
TechMaster Vietnam
Tìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tớiTìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tới
TechMaster Vietnam
iOS Master - Detail & TabBar
iOS Master - Detail & TabBariOS Master - Detail & TabBar
iOS Master - Detail & TabBar
TechMaster Vietnam
Phalcon căn bản
Phalcon căn bảnPhalcon căn bản
Phalcon căn bản
TechMaster Vietnam
Cấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phútCấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phút
TechMaster Vietnam
Phalcon introduction
Phalcon introductionPhalcon introduction
Phalcon introduction
TechMaster Vietnam
ݺߣ that wins
ݺߣ that winsݺߣ that wins
ݺߣ that wins
TechMaster Vietnam
Manage your project differently
Manage your project differentlyManage your project differently
Manage your project differently
TechMaster Vietnam
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSXHướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
TechMaster Vietnam
Go micro framework to build microservices
Go micro framework to build microservicesGo micro framework to build microservices
Go micro framework to build microservices
TechMaster Vietnam
Postgresql các vấn đề thực tế
Postgresql các vấn đề thực tếPostgresql các vấn đề thực tế
Postgresql các vấn đề thực tế
TechMaster Vietnam
Chia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTTChia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTT
TechMaster Vietnam
Cơ sở dữ liệu postgres
Cơ sở dữ liệu postgresCơ sở dữ liệu postgres
Cơ sở dữ liệu postgres
TechMaster Vietnam
Tìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tớiTìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tới
TechMaster Vietnam
Cấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phútCấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phút
TechMaster Vietnam
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSXHướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
TechMaster Vietnam

C đến C++ phần 1

  • 1. Từ C đến C++ Đơn giản mà đẹp cuong@techmaster.vn
  • 2. Khác biệt • Vào ra console • C string vs C++ string • C array vs C++ vector, array, list • Viết unit test
  • 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
  • 9. C string vs C++ string
  • 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
  • 14. string test = "Sex"; test += "y"; //Sexy const char *str = test.c_str(); //Sexy int pos = test.find("xy", 0); //2 test.substr(2, 2); //xy test.append(3, 'Y'); //SexyYYY test.erase(4, 10); //Sexy http://en.cppreference.com/w/cpp/string/basic_string http://cpp.sh/6nxf4
  • 16. Ghi file #include <iostream> #include <fstream> using namespace std; int main () { string fileName = "example.txt"; ofstream fileOut (fileName); if (fileOut.is_open()) { fileOut << "This is a line.n"; fileOut << "This is another line.n"; fileOut.close(); } else { cout << "Unable to open file"; } return 0; } http://cpp.sh/7a6c
  • 17. Đọc file string line; ifstream fileIn (fileName); if (fileIn.is_open()) { while (getline (fileIn,line) ) { cout << line << 'n'; } fileIn.close(); } else { cout << "Unable to open file"; }
  • 18. C++ vector: dynamic array array: fixed array
  • 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ó []
  • 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ó tàԳ 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
  • 39. Quản lý sinh viên • Tạo class student • Sử dụng vector để lưu trữ • Sử dụng sort để sắp xếp