std::list

list容器的倒序访问

// list::rbegin/rend
#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()来结束循环是没问题的, 这能够节省一些不必要的检查代码。

// list::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;
}

输出

mylist backwards:

list容器insert示例

// inserting into a list
#include <iostream>
#include <list>
#include <vector>
int main ()
{
std::list<int> mylist;
std::list<int>::iterator it;
// set some initial values:
for (int i=1; i<=5; ++i) mylist.push_back(i); // 1 2 3 4 5
it = mylist.begin();
++it; // it points now to number 2 ^
mylist.insert (it,10); // 1 10 2 3 4 5
// "it" still points to number 2 ^
mylist.insert (it,2,20); // 1 10 20 20 2 3 4 5
--it; // it points now to the second 20 ^
std::vector<int> myvector (2,30);
mylist.insert (it,myvector.begin(),myvector.end());
// 1 10 20 30 30 20 2 3 4 5
// ^
std::cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}