C ++向量性能:迭代器访问与括号操作员访问

时间:2013-05-03 02:05:51

标签: c++ performance vector iterator

我想知道迭代器在顺序访问设置中是否会胜过括号运算符。请考虑以下代码段:

// 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为例。)谢谢。

0 个答案:

没有答案