Data Structures & Strings in C++
One variable holds one value — but real programs need to store many values and text. This lesson covers C++'s core tools: arrays & vectors, map, and string. Bài này học các công cụ cốt lõi của C++ để lưu nhiều giá trị và văn bản: mảng & vector, map, và string.
Headers / Thư viện cần include
cpp#include <iostream> #include <vector> #include <map> #include <string> using namespace std;
📘 Section 1 — Why Collections
Making 100 separate variables is impossible. C++ gives us containers to group values, each for a different job. Không thể tạo 100 biến riêng. C++ cho ta các container để nhóm giá trị, mỗi loại cho một mục đích.
- array / vector — an ordered list of values. một danh sách giá trị có thứ tự.
- map — pairs of key → value. các cặp khóa → giá trị.
- string — a sequence of characters. một dãy ký tự.
📦 Section 2 — Arrays & Vector
An array has a fixed size. A vector<int> is a growable array — you can add items any time. Mảng có kích thước cố định. Một vector là mảng có thể lớn lên — thêm phần tử bất cứ lúc nào.
cpp// Fixed-size array int arr[3] = {10, 20, 30}; cout << arr[0] << endl; // 10 // Growable vector vector<int> nums = {1, 2, 3}; nums.push_back(4); // add to the end cout << nums.size() << endl; // 4 // Range-based loop (modern C++) for (int x : nums) { cout << x << " "; // 1 2 3 4 } cout << endl;
Reading N values / Đọc N giá trị
cppint n; cin >> n; vector<int> nums; for (int i = 0; i < n; i++) { int x; cin >> x; nums.push_back(x); }
Index from 0 / Chỉ số bắt đầu từ 0
The first element is v[0], the last is v[v.size() - 1]. Unlike Python, C++ has no negative indexing. Phần tử đầu là v[0], cuối là v[v.size()-1]. Khác Python, C++ không có chỉ số âm.
🗂️ Section 3 — map (Từ điển)
A map<string, int> stores key → value pairs — the C++ version of a Python dictionary. map lưu các cặp khóa → giá trị — phiên bản C++ của dictionary trong Python.
cppmap<string, int> ages; ages["Alice"] = 14; // add ages["Bob"] = 15; ages["Alice"] = 15; // update cout << ages["Alice"] << endl; // 15 cout << ages.count("Bob") << endl; // 1 (exists), 0 if missing ages.erase("Bob"); // remove cout << ages.size() << endl; // number of pairs
Looping over a map / Duyệt map
cppmap<string, int> ages = {{"Alice", 14}, {"Bob", 15}}; // C++11: use .first (key) and .second (value) for (auto& p : ages) { cout << p.first << " " << p.second << endl; } // C++17: structured bindings are cleaner for (auto& [name, age] : ages) { cout << name << " " << age << endl; }
map is sorted / map được sắp xếp
A std::map keeps keys in sorted order. For faster lookups without ordering, use std::unordered_map. std::map giữ khóa theo thứ tự. Cần tra cứu nhanh hơn mà không cần thứ tự thì dùng std::unordered_map.
🔤 Section 4 — std::string Basics
A string is a sequence of characters you can index, size, and join. string là một dãy ký tự bạn có thể truy cập, đo độ dài và nối.
cppstring word = "Python"; cout << word[0] << endl; // P (first character) cout << word.size() << endl; // 6 (length) cout << word.substr(0, 3) << endl; // Pyt (from index 0, length 3) string a = "Hello", b = "World"; cout << a + " " + b << endl; // Hello World a += "!"; // strings are MUTABLE in C++ cout << a << endl; // Hello!
Reading a whole line / Đọc cả dòng
cppstring line; getline(cin, line); // reads a full line, including spaces
Python vs C++ strings
Python strings are immutable and allow negative indexing. C++ std::string is mutable and has no negative index — use s[s.size() - 1] for the last character. Chuỗi Python bất biến và cho chỉ số âm. std::string thay đổi được và không có chỉ số âm.
🛠️ Section 5 — std::string Operations
cppstring s = "banana"; cout << s.find("an") << endl; // 1 (or string::npos if not found) // Uppercase, character by character for (char& c : s) { c = toupper(c); } cout << s << endl; // BANANA // Convert between numbers and text int n = stoi("42"); // string -> int string t = to_string(100); // int -> string cout << n << " " << t << endl; // 42 100
Loop over characters / Duyệt từng ký tự
Use a range-based loop for (char c : s) to visit each character — handy for counting vowels or digits. Dùng vòng lặp for (char c : s) để duyệt từng ký tự — tiện cho việc đếm nguyên âm hay chữ số.
🧩 Section 6 — Putting It Together
Count how many times each word appears — using a map and a loop (the C++ version of the Python example). Đếm số lần mỗi từ xuất hiện — dùng map và vòng lặp (phiên bản C++ của ví dụ Python).
cpp#include <iostream> #include <map> #include <string> using namespace std; int main() { map<string, int> counts; string word; while (cin >> word) { // read words until input ends counts[word]++; // starts at 0, then adds 1 } for (auto& [w, n] : counts) { cout << w << ": " << n << endl; } return 0; }
Example / Ví dụ:
Input: the cat sat on the mat
Output:
cat: 1
mat: 1
on: 1
sat: 1
the: 2Note the output is sorted by key because std::map keeps keys in order. Kết quả được sắp xếp theo khóa vì std::map giữ thứ tự.
📝 Section 7 — Practice Exercises
Exercise 1 — Reverse a Vector
Read N integers into a vector and print them in reverse order. Đọc N số nguyên vào vector và in theo thứ tự ngược.
Example Input:
5
10 20 30 40 50Example Output:
50 40 30 20 10Exercise 2 — Min and Max
Read N integers and print the smallest and the largest value in the list. Đọc N số nguyên và in giá trị nhỏ nhất và lớn nhất trong dãy.
Example Input:
6
15 42 8 23 4 16Example Output:
Min: 4
Max: 42Exercise 3 — Word Count (map)
Count how many times each word appears in the input. Đếm số lần mỗi từ xuất hiện trong dữ liệu vào.
Example Input:
the cat sat on the matExample Output: sorted by key, because std::map is ordered. sắp xếp theo khóa vì std::map có thứ tự.
cat: 1
mat: 1
on: 1
sat: 1
the: 2Exercise 4 — Reverse a String
Read a word and print it backwards (swap ends, or build a new string). Đọc một từ và in ngược lại.
Example Input:
PythonExample Output:
nohtyPExercise 5 — Count Vowels
Count the vowels in a string using a character loop. Đếm số nguyên âm trong chuỗi bằng vòng lặp ký tự.
Example Input:
programming is funExample Output:
5Exercise 6 — Uppercase a Name
Read a name and print it fully in uppercase. Đọc một tên và in ra toàn bộ bằng chữ hoa.
Example Input:
LinhExample Output:
LINHExercise 7 — Initials
Read a full name made of any number of words. Print the first letter of each word in uppercase, each one followed by a dot. Đọc một họ tên gồm số từ tùy ý. In chữ cái đầu của mỗi từ, viết hoa, mỗi chữ theo sau một dấu chấm.
Example Input:
nguyen van linhExample Output:
N.V.L.Cast toupper back to char / Ép về char
toupper returns an int, so cout prints 78 instead of N unless you write (char)toupper(word[0]). toupper trả về int — thiếu (char) thì cout in ra mã số thay vì chữ cái.
Exercise 8 — Receipt Line
Read an item name and price; print one receipt line for it. Đọc tên món và giá; in một dòng hóa đơn cho món đó.
Example Input:
Apple
25000Example Output:
Apple .... 25000 VNDWhole numbers here / Dùng số nguyên
Read the price as an int — to_string on a decimal gives 25000.000000. Đọc giá dạng int — to_string với số thực sẽ ra 25000.000000.
🚀 Section 8 — Challenge: Contact Book
Build a contact book using a map<string, string> of name → phone. Xây một sổ danh bạ dùng map tên → số điện thoại.
Example Input:
add Minh 0987654321
add Linh 0901234567
find Linh
find Nam
list
quitExample Output:
Linh: 0901234567
Not found
Linh: 0901234567
Minh: 0987654321cppmap<string, string> contacts; string action; while (cin >> action) { if (action == "add") { string name, phone; cin >> name >> phone; contacts[name] = phone; } else if (action == "find") { string name; cin >> name; if (contacts.count(name)) cout << name << ": " << contacts[name] << endl; else cout << "Not found" << endl; } else if (action == "list") { for (auto& [name, phone] : contacts) cout << name << ": " << phone << endl; } else if (action == "quit") { break; } }
Summary & Python ↔ C++ / Tóm tắt
- Python
list→ C++vector<T>(push_back,size). - Python
dict→ C++map<K, V>(access with[ ], check withcount). - Python
str→ C++string— mutable, no negative index, usesubstr/find/stoi.