C++20中的基于范围的for循环(range-based for loop)

C++11中引入了对基于范围的for循环(range-based for loop)的支持:该循环对一系列值(例如容器中的所有元素)进行操作。代码段如下:

cpp 复制代码
const std::vector<int> vec{ 1,2,3,4,5 };
for (const auto& i : vec)
    std::cout << i << ", ";
std::cout << std::endl;

C++17中增加对结构化绑定(structured bingding)声明的支持。代码段如下:

cpp 复制代码
std::map<int, int> m{ {1,-1}, {2,-2}, {3,-3} };
for (const auto& [key, value] : m)
    std::cout << key << "," << value << "; ";
std::cout << std::endl;

C++20中增加支持声明任意多个变量,必须以分号结尾。代码段如下:

cpp 复制代码
const std::vector<int> vec{ 1,2,3,4,5 };
for (auto n = vec.size(), m = static_cast<size_t>(0); const auto & i : vec)
	std::cout << --n + i << "," << ++m << "; ";
std::cout << std::endl;

for (const auto vec = std::vector{ -1,-2,-3,-4,-5 }; const auto& i : vec)
	std::cout << i << ", ";
std::cout << std::endl;

以下为完整测试代码:

cpp 复制代码
int test_for_20()
{
	const std::vector<int> vec{ 1,2,3,4,5 };
	// C++11
	for (const auto& i : vec)
		std::cout << i << ", ";
	std::cout << std::endl;

	// C++17
	std::map<int, int> m{ {1,-1}, {2,-2}, {3,-3} };
	for (const auto& [key, value] : m)
		std::cout << key << "," << value << "; ";
	std::cout << std::endl;

	// C++20
	for (auto n = vec.size(), m = static_cast<size_t>(0); const auto & i : vec)
		std::cout << --n + i << "," << ++m << "; ";
	std::cout << std::endl;

	for (const auto vec = std::vector{ -1,-2,-3,-4,-5 }; const auto& i : vec)
		std::cout << i << ", ";
	std::cout << std::endl;


	return 0;
}

执行结果如下图所示:

GitHubhttps://github.com/fengbingchun/Messy_Test