C++ 语言特性15 - 基于范围的for循环
1. C++11的 for 循环
//C++11的for循环语法
for (declaration : range_expression) {// loop body
}//declaration:声明一个变量,该变量在每次迭代中被初始化为序列中的下一个值。
//range_expression:一个表达式,它返回一个迭代器范围,通常是容器或数组。//例子1
#include <vector>
#include <string>std::vector<std::string> fruits = {"apple", "banana", "cherry"};
for (const std::string& fruit : fruits) {std::cout << fruit << std::endl;
}//例子2
int myArray[] = {1, 2, 3, 4, 5};
for (int x : myArray) {std::cout << x << std::endl;
}//例子3
#include <map>
#include <iostream>std::map<std::string, int> ages = {{"Alice", 30},{"Bob", 25},{"Charlie", 35}
};for (const auto& pair : ages) {std::cout << pair.first << " is " << pair.second << " years old." << std::endl;
}
2. C++ 20中的 for 循环
//C++20
for ( init-statement for-range-declaration : for-range-expression ) {loop-statement;
}
//init-statement:在循环开始之前执行的语句,可以用于初始化变量或执行其他操作
//for-range-declaration:可以是变量声明,也可以是类型定义(C++20新特性)//例子1
int total = 0;
for (auto n = 10; auto x : std::vector<int>{1, 2, 3, 4, 5}) {total += x * n;
}
std::cout << "Total: " << total << std::endl; // 输出 Total: 70//例子2
//**********************************************************
#include <iostream>
#include <vector>
#include <string>
#include <map>int main() {std::vector<int> v = {1, 2, 3, 4, 5};for (auto x : v) {std::cout << x << " ";}std::cout << "\n";std::map<std::string, int> m = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};for (const auto& [name, age] : m) {std::cout << name << ": " << age << "\n";}for (auto n = 3; auto i : std::vector<int>{0, 1, 2, 3}) {std::cout << n * i << " ";}std::cout << "\n";for (using elem_t = int; elem_t i : std::vector<elem_t>{1, 2, 3}) {std::cout << i << " ";}std::cout << "\n";return 0;
}
3. 如何在自定义类中支持基于范围的for循环
为了在自定义类中支持基于范围的 for
循环,需要确保自定义类可以被迭代。这通常意味着需要提供 begin()
和 end()
方法,这样标准库的 std::begin
和 std::end
就可以使用这些方法来获取迭代器。
-
定义迭代器:为自定义类定义一个迭代器,这个迭代器至少需要支持
++
、*
和!=
操作。 -
提供
begin()
和end()
方法:在自定义类中提供begin()
和end()
方法,它们分别返回指向第一个元素和末尾的迭代器。 -
(可选)支持
const
迭代器:如果希望自定义类在const
上下文中也能被迭代,应该提供const
版本的begin()
和end()
方法。
#include <iostream>
#include <vector>class MyRange {
private:std::vector<int> data_;public:// 构造函数MyRange(std::initializer_list<int> list) : data_(list) {}// 返回到开始的迭代器auto begin() {return data_.begin();}// 返回到结束的迭代器auto end() {return data_.end();}// const 迭代器版本auto begin() const {return data_.begin();}auto end() const {return data_.end();}
};int main() {MyRange range({1, 2, 3, 4, 5});// 使用基于范围的for循环for (const int& value : range) {std::cout << value << " ";}std::cout << std::endl;return 0;
}