gpt4 book ai didi

c++ - C++中迭代器的指针如何在循环中变化?

转载 作者:太空狗 更新时间:2023-10-29 23:40:35 26 4
gpt4 key购买 nike

我在 C++ 中玩弄 vector,我发现了这个问题,我很困惑......

#include <vector>
#include <cstdio>
using namespace std;

int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
printf("At: %p, %i\n", &it, *it);
}
}

我确实运行了这个程序

g++ -Wall soquestion.cpp -o soquestion
./soquestion

输出

At: 0x7fff59c80a98, 1
At: 0x7fff59c80a98, 2
At: 0x7fff59c80a98, 3

但我认为 it 的地址每次都递增??

最佳答案

printf("At: %p, %i\n", &*it, *it);

这将向您展示我假设您想要的。 vector 中所选对象的地址后跟 vector 中所选对象的值。就像 duffymo 所说的那样,之前您引用的是实际的 it 对象本身,而不是它所指向的对象。

关于c++ - C++中迭代器的指针如何在循环中变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18664837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com