c++ - 了解 vector 中的.begin和.end

标签 c++ vector auto

我正在从this post学习 vector ,它们以迭代器开始。他们定义.begin和.end如下:

begin() – Returns an iterator pointing to the first element in the vector

end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector



然后,他们给出了以下代码片段,我添加了第3个for循环来表达我的问题。
#include<iostream>
#include<vector>

int main() {
    std::vector <int> g1; //creating a vector
    for (int i = 1; i <= 3; i++){
        g1.push_back(i);
    }
    std::cout << "Output of beginning and end values: ";
    for (auto i = g1.begin(); i != g1.end(); i++) {
        std::cout << *i << " "; 
    }
    std::cout << "\nOutput of beginning and end addresses: ";
    for (auto i = g1.begin(); i != g1.end(); i++) {
        std::cout << &i << " ";
    }
     //"Output of beginning and end values: 1 2 3"
     //"Output of beginning and end addresses: 0105FB0C 0105FB0C 0105FB0C"
    return 0;
}

我的困惑是i的地址保持不变,但是i的值已更改。 i*是不是意味着i刚刚被取消引用?因此,如果地址不变,则必须更改i的值,以便它可以具有不同的值。我想可能会使迭代器与指针混淆。我知道auto基本上是类型推断,仅此而已。

所以我的问题是,如果 vector 中每个元素的地址都相同,i的值将如何变化?

最佳答案

&i是局部变量i的地址。这不会改变。 *i取消引用迭代器,并返回 vector 中该元素的值。 &*i将返回一个指向 vector 中元素的指针。

所以你循环应该使用

std::cout << &*i << " ";

查看地址更改。

关于c++ - 了解 vector 中的.begin和.end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867350/

相关文章:

c++ - std::bind 如何多次调用复制构造函数

c++ - 双向链表中的访问冲突

r - 使用索引的倍数来保留或替换向量中的值

c++ - 为什么我不能将 T* 包装在 std::vector<T> 中?

c++ - 如何将多个值 push_back 到一个 vector 中?

c++ - 为什么我不能将 auto 与 std::thread 一起使用?

C++11 自动 : what if it gets a constant reference?

C++: 读取数字数据直到\n

c++ - 将 32 位地址的类型转换为 (BYTE *) 和 (DWORD *) 有什么区别

c++ - Qt中会自动断开连接吗?