标准模板库iter_swap函数

在学c++容器的时候遇到了问题。
iter_swap函数,交换的是两个迭代器所指的值,按理说交换后应该两个迭代器所指的位置应该不变,可在vs上运行显示交换后两个迭代器的位置都发生了改变,不是很理解。


#include
#include
#include
#include
using namespace std;
int main() {
    int a[5] = { 1,2,3,4,5 };
    list<int>lst(a, a + 5);
    list<int>::iterator p=lst.begin();
    advance(p, 1);
    printf("p的开始位置:%p\n", p);
    list<int>::iterator q = lst.end();
    q--;
    printf("q的开始位置:%p\n",q);
    iter_swap(p, q);
    printf("p的交换后位置:%p\n", p);
    printf("q的交换后位置:%p\n", q);
    return 0;

}

img

该回答引用ChatGPT

试一下这个代码


#include<iostream>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;
int main() {
    int a[5] = { 1,2,3,4,5 };
    list<int>lst(a, a + 5);
    list<int>::iterator p=lst.begin();
    advance(p, 1);
    cout << "p的开始位置:" << &(*p) << endl;
    list<int>::iterator q = lst.end();
    q--;
    cout << "q的开始位置:" << &(*q) << endl;
    iter_swap(p, q);
    cout << "p的交换后位置:" << &(*p) << endl;
    cout << "q的交换后位置:" << &(*q) << endl;
    return 0;
}