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

std::distance not giving expected output

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;
}

输出为

5: 5
4: 5
3: 5
2: 5
1: 5

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

5: 5
4: 4
3: 3
2: 2
1: 1

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

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

static int index_dif = distance(i, q.rend());

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

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

这是 demo