数组和容器上的 C 风格迭代容易出现索引错误并且输入繁琐。 知道如何消除这些错误并使用现代 C++ 风格使代码更具可读性。
问: 请 转换下面的旧式代码以在标准库容器和原始数组上使用基于范围的 for 循环。 您应该修复任何运行时错误,使用 for 循环初始化,并首选 constexpr 变量作为编译时常量。
#define SIZE 21 // C-style
std::vector<int> v{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 };
// C-style
for (int i = 0; i < v.size(); ++i)
{
std::cout << v[i];
}
int* arr = new int[SIZE];
for (int i = 0; i < SIZE; ++i) {
arr[i] = v.at(i);
std::cout << arr[i];
}
由于某些标准库中不支持下标访问,但是支持迭代器,所以统一使用迭代器
要使用constexpr必须初始化为常量,会导致编译失败
#include <iostream>
#include <vector>
#define SIZE 21 // C-style
using namespace std;
int main(){
vector<int> v;
for(int i=0;i<SIZE;++i){
v.push_back(i);
}
for (auto it = v.begin(); it!=v.end(); ++it)
{
cout << *it;
}
int arr[SIZE];
for(auto i:v){
arr[i]=v.at(i);
}
return 0;
}
基于范围的for循环就是for(变量:容器),在这道题是
for(int i:v)
std::cout<<i;