Phần 1
1. Goal
After learning range-based for loops, you should understand:
1. Why C++11 introduced range-based for.
2. The minimum syntax.
3. The difference between copy, reference, and const reference.
4. Common mistakes when iterating over containers.
5. How to use range-based for in performance-sensitive code.Phần 2
2. What Problem Does It Solve?
Before C++11, iterating over containers often required manual indexes or iterators:
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)Range-based for makes iteration shorter, cleaner, and less error-prone:
for (auto x : v)Main idea:
Iterate directly over elements instead of manually managing indexes or iterators.Phần 3
3. Minimum Syntax
Copy each element:
for (auto x : container)Modify the real element:
for (auto& x : container)Read without copying:
for (const auto& x : container)Summary:
auto = copy
auto& = reference, can modify
const auto& = read-only reference, avoids copyingPhần 4
4. Common Mistakes
4.1. Forgetting & when modifying elements
for (auto x : values) {
x = 0;
}This only modifies the copy, not the original container.
Use:
for (auto& x : values) {
x = 0;
}4.2. Copying heavy objects
for (auto order : orders)This copies every order.
If you only read the data, prefer:
for (const auto& order : orders)4.3. Modifying a container while iterating
Be careful when adding or removing elements during iteration.
This may invalidate references or iterators, especially with containers like std::vector.
Phần 5
5. When Should You Use It?
Use range-based for when:
1. You want to visit every element.
2. You do not need the index.
3. The iteration order is simple.
4. The code should be clean and readable.Avoid it when:
1. You need the index.
2. You need to erase elements while iterating.
3. You need complex iterator control.Phần 6
6. Notes for Trading / Performance-Sensitive Code
In trading systems, containers may store many objects:
Order
Trade
Tick
MarketData
PositionFor large objects, avoid unnecessary copies:
for (const auto& order : orders)Use references when updating real objects:
for (auto& position : positions)Use copies only for small objects like int, double, or when you intentionally need a copy.
Phần 7
7. End-of-Day Checklist
You should remember:
for (auto x : c) -> copy
for (auto& x : c) -> modify original
for (const auto& x : c) -> read-only, no copyYou should be able to answer:
1. Why is range-based for cleaner than iterator loops?
2. When does `auto` copy?
3. When should you use `auto&`?
4. Why is `const auto&` important for large objects?
5. When should you avoid range-based for?Phần 8
8. Conclusion
Range-based for is a simple but important C++11 feature.
The key idea:
Use range-based for when you want to iterate over every element clearly.
Choose auto, auto&, or const auto& depending on copy, modification, and performance needs.:::
Mã mẫu hoàn chỉnh
cpp11/3_range-based for/main.cpp
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
struct Position {
std::string symbol;
int quantity;
double last_price;
};
double calculateTotalMarketValue(const std::vector<Position>& positions) {
double total = 0.0;
for (const auto& pos : positions) {
total += pos.quantity * pos.last_price;
}
return total;
}
void printPositions(const std::vector<Position>& positions) {
std::cout << "Current positions:\n";
for (const auto& pos : positions) {
std::cout << pos.symbol
<< " | qty = " << pos.quantity
<< " | last_price = " << std::fixed << std::setprecision(2)
<< pos.last_price
<< '\n';
}
}
int main() {
std::vector<Position> positions = {
{"AAPL", 100, 191.25},
{"MSFT", 50, 420.50},
{"NVDA", 10, 875.10}
};
printPositions(positions);
double total_value = calculateTotalMarketValue(positions);
std::cout << "\nTotal market value = "
<< std::fixed << std::setprecision(2)
<< total_value << "\n\n";
return 0;
}Tự kiểm tra · không chấm điểm
Bạn đã hiểu những điểm nào?
Đã tự kiểm tra 0/5 mục