STL iter_swap()其中参数为什么是--col1.end()。

#include
#include
#include
#include
using namespace std;

int main()
{
int A[]={1,2,3,4,5};
const int N = sizeof(A)/sizeof(int);
list col1(A,A+N);
ostream_iterator output(cout," ");

cout<<"List col1 contains:";
copy(col1.begin(),col1.end(),output);

list<int>::iterator pos = col1.begin();
cout<<"The first element is:"<<*pos<<endl;
advance(pos,3);
cout<<"the 4th element is:"<<*pos<<endl;
cout<<"The advanced distance is:"<<distance(col1.begin(),pos);
iter_swap(col1.begin(),--col1.end());
cout<<"After exchange list col1 contains:";
copy(col1.begin(),col1.end(),output);
return 0;

}
倒数第四行的iter_swap()函数中为什么 是--col1.end(),该句功能是交换列表容器的第一个元素和最后一个元素。
图片说明


因为col.end()迭代器指向的 并不是容器的最后一个元素,而是one past the end元素,用于标记容器结束的一个位置,对col.end()进行解引用会导致未定义的结果。实际上,--col1.end()也就是col.end()往前的一个元素才是容器最后的元素。

我的博客里有list与map实现代码可以参考下。