std::distance 没有给出预期的输出

not*_*lso 0 c++ reverse for-loop distance stdvector

std::distance 在 for 循环中返回相同的值,尽管其中一个参数在每个循环中都发生了变化。

#include <vector>
#include <iostream>

using namespace std;

int main() {
    vector<int> q{1, 2, 3, 4, 5};
    for (auto i = q.rbegin(); i != q.rend(); i++) {
        static int index_dif = distance(i, q.rend());
        cout << *i << ": " << index_dif << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是

5: 5
4: 5
3: 5
2: 5
1: 5
Run Code Online (Sandbox Code Playgroud)

尽管i每个循环都会增加,所以我希望q.rend()它之间的距离随着循环的进行而缩小,如下所示:

5: 5
4: 4
3: 3
2: 2
1: 1
Run Code Online (Sandbox Code Playgroud)

相反,它似乎给人之间的距离q.rbegin()q.rend()每一次。

cig*_*ien 5

static 变量只初始化一次,所以这一行:

static int index_dif = distance(i, q.rend());
Run Code Online (Sandbox Code Playgroud)

将只使用的第一个值i来初始化index_dif

删除static,您应该会看到预期的输出。

这是一个演示