根据我所学到的迭代容器的方法,如 std::vector,是使用迭代器,如下所示:
for(vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
我的问题是为什么不使用 standatd 迭代容器for
,它更快,因为不需要调用函数 asnumbers.begin()
和numbers.end()
。
根据我的尝试,我发现for
使用迭代器更快 X 30。
我写了这段代码:
vector<int> numbers;
for (int i = 0; i < 5000000; i++)
{
numbers.push_back(i);
}
time_t t = time(0);
struct tm * now = localtime(&t);
cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << "\n";
for(vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
*it = 7;
}
t = time(0);
now = localtime(&t);
cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << "\n";
int size = numbers.size();
for (int i = 0; i < size; i++)
{
numbers[i] = i;
}
t = time(0);
now = localtime(&t);
cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec;
输出是:
19:28:25
19:28:56
19:28:57