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.

📘 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.

📦 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ị

cpp
int n; cin >> n; vector<int> nums; for (int i = 0; i < n; i++) { int x; cin >> x; nums.push_back(x); }

🗂️ 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.

cpp
map<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

cpp
map<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; }

🔤 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.

cpp
string 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

cpp
string line; getline(cin, line); // reads a full line, including spaces

🛠️ Section 5 — std::string Operations

cpp
string 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

🧩 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: 2

Note 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 50

Example Output:

50 40 30 20 10

Exercise 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 16

Example Output:

Min: 4
Max: 42

Exercise 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 mat

Example 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: 2

Exercise 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:

Python

Example Output:

nohtyP

Exercise 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 fun

Example Output:

5

Exercise 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:

Linh

Example Output:

LINH

Exercise 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 linh

Example Output:

N.V.L.

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
25000

Example Output:

Apple .... 25000 VND

🚀 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
quit

Example Output:

Linh: 0901234567
Not found
Linh: 0901234567
Minh: 0987654321
cpp
map<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