我想知道迭代器在顺序访问设置中是否会胜过括号运算符。考虑以下代码片段:
// v1.1
for (std::vector<int>::const_iterator it = v.begin(); it != v.end(); ++it) {
do_something(*it);
}
// v1.2
for (size_t i = 0; i != v.size(); ++i) {
do_something(v[i]);
}
// v1.3
std::vector<int>::const_iterator endIt = v.end();
for (std::vector<int>::const_iterator it = v.begin(); it != endIt; ++it)
do_something(*it);
}
// v1.4
size_t size = v.size();
for (size_t i = 0; i != size; ++i) {
do_something(v[i]);
}
// v2.1
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
*it = it - v.begin(); // iterator arithmetic; expensive or not?
}
// v2.2
for (size_t i = 0; i != v.size(); ++i) {
v[i] = i;
}
有没有人为这些做过基准测试?(嗯,这取决于编译器;我们以 g++ 4.7 或 4.8 为例。)谢谢。