Sunday, February 24, 2013

[C++] 小探iterator

#include <iostream>
#include <map>

using namespace std;

main() {
    map<int int> a;
    map<int int>::const_iterator cit;
    map<int int>::iterator it;
    a[1] = 15;
    printf("&a[1] = %p a[1] = %d\n", &a[1], a[1]);
    cit = a.find(1);
    it = a.find(1);
    it->second = 255;
    printf("%lx %p %d\n", *((long*) &it), &(it->second), it->second);
    printf("%lx %p %d\n", *((long*) &cit), &(cit->second), cit->second);
}
运行结果:
$ ./a.out
&a[1] = 0x7fb58a403954 a[1] = 15
&it =0x7fff520aa898 it =7fb58a403930 &(it->second) =0x7fb58a403954 it->second =255
&cit=0x7fff520aa8a0 cit=7fb58a403930 &(cit->second)=0x7fb58a403954 cit->second=255
几个结论:
  • 从cit只占用8个字节大小来看(&it-&cit), map::const_iterator 或者map::iterator, 其实内容就是一个8-byte的指针
  • 从cit和it都存着同样内容(0x7fff520aa898)来看, 内容其实就是map中该元素的地址.
  • 而且iterator的first 和second并不是值拷贝. 比如我们使用it对a[1]的值更新后, const_iterator只是该iterator不能对map做改动而已.

No comments: