20230409 STL内存相关

既然迭代器不能直接打出来(第三句不能直接运行)
就是没有相应输出流啥啥的
反正前面两句显示的都不是我想要的数据
不对第一句是去访问it里面的地址
实际上也就是第一个元素的值??????
对啊,运行出来就是这样的你在想什么
在 C++ 中,迭代器是一个用于访问容器中元素的对象。迭代器是一个指针对象,用于指向容器中的元素。每个迭代器实例都指向容器中的一个特定元素。当对迭代器进行解引用操作时,会返回一个指向元素的引用或指针。
在容器中,每个元素在内存中都有一个唯一的地址。因此,迭代器可以通过访问容器中每个元素的地址来遍历容器。
当我们在使用迭代器访问容器元素时,不同迭代器实例所取得的元素地址可能不同。这是因为在容器中,每个元素在内存中都有一个唯一的地址,不同元素的地址是不同的。因此,不同迭代器实例所取得的元素地址可能不同。
然而,对于同一个迭代器实例,它所取得的元素地址是相同的。这是因为在迭代器实例被创建后,它指向的元素地址是固定的,直到迭代器被递增或递减时才会改变。因此,对于同一个迭代器实例,它所取得的元素地址是不变的。
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| #include<iostream> #include<vector>
using namespace std;
void test01() { vector<int>* a = new vector<int>(4, 2); vector<int>* b = new vector<int>(3, 2);
cout << &a << endl; cout << &b << endl; cout << a << endl; cout << b << endl;
vector<int>::iterator it = a->begin(); for (; it != a->end(); it++) { cout << *it << endl;
} cout << "********************" << endl;
it = b->begin(); for (; it != b->end(); it++) { cout << *it << endl;
}
cout << a->size() << endl; cout << b->size() << endl; cout << a->capacity() << endl; cout << b->capacity() << endl;
a->push_back(88); a->push_back(88);
cout << &a << endl; cout << &b << endl; cout << a << endl; cout << b << endl; cout << a->size() << endl; cout << b->size() << endl; cout << a->capacity() << endl; cout << b->capacity() << endl;
it = a->begin(); for (; it != a->end(); it++) { cout << *it << endl;
} cout << "********************" << endl;
it = b->begin(); for (; it != b->end(); it++) { cout << *it << endl;
}
}
void test02() {
vector<int> c(2, 2); vector<int> d(3, 2);
cout << &c << endl; cout << &d << endl; cout << c.size() << endl; cout << d.size() << endl; cout << c.capacity() << endl; cout << d.capacity() << endl; cout << "********************" << endl; for (int i = 0; i < c.size(); i++) { cout << &c[i] << endl; } cout << "********************" << endl;
for (int i = 0; i < d.size(); i++) { cout << &d[i] << endl; }
c.push_back(55); c.push_back(55); c.push_back(55); c.push_back(55); c.push_back(55); c.push_back(55); c.push_back(55);
cout << "********************" << endl; cout << &c << endl; cout << &d << endl;
cout << c.size() << endl; cout << d.size() << endl;
cout << c.capacity() << endl; cout << d.capacity() << endl;
for (int i = 0; i < c.size(); i++) { cout << &c[i] << endl; } cout << "********************" << endl;
for (int i = 0; i < d.size(); i++) { cout << &d[i] << endl; }
}
int main() { test02(); return 0; }
|
可以发现在扩容之后元素首地址以及元素地址们都已经发生改变
但是对容器本身取地址却发现没有变化
