SlideShare a Scribd company logo
1 of 39
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 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ó []
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ó thành 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 hành
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

Bài tập nhập môn lập trình
Bài tập nhập môn lập trìnhBài tập nhập môn lập trình
Bài tập nhập môn lập trình
Huy Rùa
 
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
 
đáP án 24 đề tin
đáP án 24 đề tinđáP án 24 đề tin
đáP án 24 đề tin
Ttx Love
 
Tóm tắt công thức vật lý 12, luyện thi đại học
Tóm tắt công thức vật lý 12, luyện thi đại họcTóm tắt công thức vật lý 12, luyện thi đại học
Tóm tắt công thức vật lý 12, luyện thi đại học
Trong Nguyen
 
Bài giảng phương pháp số ths.phan thị hà[bookbooming.com]
Bài giảng phương pháp số   ths.phan thị hà[bookbooming.com]Bài giảng phương pháp số   ths.phan thị hà[bookbooming.com]
Bài giảng phương pháp số ths.phan thị hà[bookbooming.com]
bookbooming1
 
De xstk k11
De xstk k11De xstk k11
De xstk k11
dethinhh
 

What's hot (20)

Bài tập nhập môn lập trình
Bài tập nhập môn lập trìnhBài tập nhập môn lập trình
Bài tập nhập môn lập trình
 
Giai nhanh phuong phap tinh
Giai nhanh phuong phap tinhGiai nhanh phuong phap tinh
Giai nhanh phuong phap tinh
 
Biến ngẫu nhiên liên tục - Xác suất thống kê
Biến ngẫu nhiên liên tục - Xác suất thống kêBiến ngẫu nhiên liên tục - Xác suất thống kê
Biến ngẫu nhiên liên tục - Xác suất thống kê
 
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
 
đáP án 24 đề tin
đáP án 24 đề tinđáP án 24 đề tin
đáP án 24 đề tin
 
Đại số boolean và mạch logic
Đại số boolean và mạch logicĐại số boolean và mạch logic
Đại số boolean và mạch logic
 
Ly thuyet-va-cong-thuc-cac-dang-dddh.thuvienvatly.com.d4cde.19191
Ly thuyet-va-cong-thuc-cac-dang-dddh.thuvienvatly.com.d4cde.19191Ly thuyet-va-cong-thuc-cac-dang-dddh.thuvienvatly.com.d4cde.19191
Ly thuyet-va-cong-thuc-cac-dang-dddh.thuvienvatly.com.d4cde.19191
 
Toán rời rạc-Dành cho sinh viên,người thi cao học
Toán rời rạc-Dành cho sinh viên,người thi cao họcToán rời rạc-Dành cho sinh viên,người thi cao học
Toán rời rạc-Dành cho sinh viên,người thi cao học
 
biến đổi ma trận ( Transformation matrix)
biến đổi ma trận ( Transformation matrix)biến đổi ma trận ( Transformation matrix)
biến đổi ma trận ( Transformation matrix)
 
TÀI LIỆU GIẢNG DẠY THỰC HÀNH VẬT LÝ ĐẠI CƯƠNG A1
TÀI LIỆU GIẢNG DẠY THỰC HÀNH VẬT LÝ ĐẠI CƯƠNG A1 TÀI LIỆU GIẢNG DẠY THỰC HÀNH VẬT LÝ ĐẠI CƯƠNG A1
TÀI LIỆU GIẢNG DẠY THỰC HÀNH VẬT LÝ ĐẠI CƯƠNG A1
 
Bai tap java
Bai tap javaBai tap java
Bai tap java
 
Lập trình Python cơ bản
Lập trình Python cơ bảnLập trình Python cơ bản
Lập trình Python cơ bản
 
Bo de-thi-va-loi-giai-xac-xuat-thong-ke
Bo de-thi-va-loi-giai-xac-xuat-thong-keBo de-thi-va-loi-giai-xac-xuat-thong-ke
Bo de-thi-va-loi-giai-xac-xuat-thong-ke
 
Lập trình hướng đối tượng - p3
Lập trình hướng đối tượng - p3Lập trình hướng đối tượng - p3
Lập trình hướng đối tượng - p3
 
30 bài toán phương pháp tính
30 bài toán phương pháp tính30 bài toán phương pháp tính
30 bài toán phương pháp tính
 
Tóm tắt công thức vật lý 12, luyện thi đại học
Tóm tắt công thức vật lý 12, luyện thi đại họcTóm tắt công thức vật lý 12, luyện thi đại học
Tóm tắt công thức vật lý 12, luyện thi đại học
 
Hướng dẫn giải bài tập Đại Số Tuyến Tính
Hướng dẫn giải bài tập Đại Số Tuyến TínhHướng dẫn giải bài tập Đại Số Tuyến Tính
Hướng dẫn giải bài tập Đại Số Tuyến Tính
 
Hướng dẫn làm bt về chuỗi.doc
Hướng dẫn làm bt về chuỗi.docHướng dẫn làm bt về chuỗi.doc
Hướng dẫn làm bt về chuỗi.doc
 
Bài giảng phương pháp số ths.phan thị hà[bookbooming.com]
Bài giảng phương pháp số   ths.phan thị hà[bookbooming.com]Bài giảng phương pháp số   ths.phan thị hà[bookbooming.com]
Bài giảng phương pháp số ths.phan thị hà[bookbooming.com]
 
De xstk k11
De xstk k11De xstk k11
De xstk k11
 

Similar to C đến C++ phần 1

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
 
C10 generic algorithms
C10 generic algorithmsC10 generic algorithms
C10 generic algorithms
Hồ Lợi
 
Ctdl C03
Ctdl C03Ctdl C03
Ctdl C03
giang
 
Cpl test1%20key
Cpl test1%20keyCpl test1%20key
Cpl test1%20key
Hồ Lợi
 
4 Pointer String Struct
4 Pointer String  Struct4 Pointer String  Struct
4 Pointer String Struct
Cuong
 

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
 
Basic C programming
Basic C programmingBasic C programming
Basic C programming
 
Lec3. Ham.pdf
Lec3. Ham.pdfLec3. Ham.pdf
Lec3. Ham.pdf
 
C10 generic algorithms
C10 generic algorithmsC10 generic algorithms
C10 generic algorithms
 
C10 generic algorithms
C10 generic algorithmsC10 generic algorithms
C10 generic algorithms
 
Tut4 solution
Tut4 solutionTut4 solution
Tut4 solution
 
Nang cao c++
Nang cao c++Nang cao c++
Nang cao c++
 
Advcpp good
Advcpp goodAdvcpp good
Advcpp good
 
Lect09 string
Lect09 stringLect09 string
Lect09 string
 
String c++
String c++String c++
String c++
 
Chapter04_Array_chinhsua
Chapter04_Array_chinhsuaChapter04_Array_chinhsua
Chapter04_Array_chinhsua
 
Stl string
Stl stringStl string
Stl string
 
Control structure in C
Control structure in CControl structure in C
Control structure in C
 
Ctdl C03
Ctdl C03Ctdl C03
Ctdl C03
 
Tut6 solution
Tut6 solutionTut6 solution
Tut6 solution
 
Cpl test1%20key
Cpl test1%20keyCpl test1%20key
Cpl test1%20key
 
Chuong1 c
Chuong1 c Chuong1 c
Chuong1 c
 
Session 11
Session 11Session 11
Session 11
 
Session 11
Session 11Session 11
Session 11
 
4 Pointer String Struct
4 Pointer String  Struct4 Pointer String  Struct
4 Pointer String Struct
 

More from TechMaster Vietnam

More from TechMaster Vietnam (20)

Neural Network from Scratch
Neural Network from ScratchNeural Network from Scratch
Neural Network from Scratch
 
Go micro framework to build microservices
Go micro framework to build microservicesGo micro framework to build microservices
Go micro framework to build microservices
 
Flutter vs React Native 2018
Flutter vs React Native 2018Flutter vs React Native 2018
Flutter vs React Native 2018
 
Authentication and Authorization
Authentication and AuthorizationAuthentication and Authorization
Authentication and Authorization
 
Postgresql security
Postgresql securityPostgresql security
Postgresql security
 
Knex Postgresql Migration
Knex Postgresql MigrationKnex Postgresql Migration
Knex Postgresql Migration
 
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ế
 
Arrowjs.io
Arrowjs.ioArrowjs.io
Arrowjs.io
 
Minimum Viable Products
Minimum Viable ProductsMinimum Viable Products
Minimum Viable Products
 
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
 
Cơ sở dữ liệu postgres
Cơ sở dữ liệu postgresCơ sở dữ liệu postgres
Cơ sở dữ liệu postgres
 
Node.js căn bản
Node.js căn bảnNode.js căn bản
Node.js căn bản
 
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
 
iOS Master - Detail & TabBar
iOS Master - Detail & TabBariOS Master - Detail & TabBar
iOS Master - Detail & TabBar
 
Phalcon căn bản
Phalcon căn bảnPhalcon căn bản
Phalcon căn bản
 
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
 
Phalcon introduction
Phalcon introductionPhalcon introduction
Phalcon introduction
 
Slide that wins
Slide that winsSlide that wins
Slide that wins
 
Manage your project differently
Manage your project differentlyManage your project differently
Manage your project differently
 
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
 

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
  • 19.
  • 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
  • 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