list容器的倒序访问
#include <iostream>
#include <list>
int main ()
{
std::list<int> mylist;
for (int i=1; i<=5; ++i) mylist.push_back(i);
std::cout << "mylist backwards:";
for (std::list<int>::reverse_iterator rit=mylist.rbegin(); rit!=mylist.rend(); ++rit)
std::cout << ' ' << *rit;
std::cout << '\n';
return 0;
}
输出
mylist backwards:5 4 3 2 1
list容器为空时的迭代结束条件
容器为空时,begin()==end(),rbegin()==rend(),所以不需要先判断是不是空,直接用rbegin()!=rend()来结束循环是没问题的, 这能够节省一些不必要的检查代码。
#include <iostream>
#include <list>
int main ()
{
std::list<int> mylist;
std::cout << "mylist backwards:";
for (std::list<int>::reverse_iterator rit=mylist.rbegin(); rit!=mylist.rend(); ++rit)
std::cout << ' ' << *rit;
std::cout << '\n';
return 0;
}
输出
list容器insert示例
#include <iostream>
#include <list>
#include <vector>
int main ()
{
std::list<int> mylist;
std::list<int>::iterator it;
for (int i=1; i<=5; ++i) mylist.push_back(i);
it = mylist.begin();
++it;
mylist.insert (it,10);
mylist.insert (it,2,20);
--it;
std::vector<int> myvector (2,30);
mylist.insert (it,myvector.begin(),myvector.end());
std::cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}