t will contain -1,0,1,2,3,4,5,6,7,8,9,10
*/
list1.insert(list1.end(), 10);
/*
|| Inserting a range from another container
|| Our list will contain -1,0,1,2,3,4,5,6,7,8,9,10,11,12
*/
int IntArray[2] = {11,12};
list1.insert(list1.end(), &IntArray[0], &IntArray[2]);
/*
|| As an exercise put the code in here to print the lists!
|| Hint: use PrintIt and accept an interger
*/
//output
for(List1Itetator=list1.begin();List1Itetator!=list1.end();
List1Itetator++)
{
cout<<*List1Itetator<<endl;
}
}
注意,insert()函数把一个或若干个元素插入到你指出的iterator的位置。你的元素将出现在 iterator指出的位置以前。
13 List 构造函数
我们已经象这样定义了list:
list<int> Fred;
你也可以象这样定义一个list,并同时初始化它的元素:
// define a list of 10 elements and initialise them all to 0
list<int> Fred(10, 0);
// list now contains 0,0,0,0,0,0,0,0,0,0
或者你可以定义一个list并用另一个STL容器的一个范围来初始化它,这个STL容器不一定是一个list, 仅仅需要是元素类型相同的的容器就可以。
vector<int> Harry;
Harry.push_back(1);
Harry.push_back(2);
#
// define a list and initialise it with the elements in Harry
list<int> Bill(Harry.begin(), Harry.end());
// Bill now contains 1,2 14 使用list成员函数从list中删除元素
list成员函数pop_front()删掉list中的第一个元素,pop_back()删掉最后一个元素。函数erase()删掉由一个iterator指出的元素。还有另一个erase()函数可以删掉一个范围的元素。
/*
|| Erasing objects from a list
*/
#include <list>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
void main (void) {
list<int> list1; // define a list of integers
/*
|| Put some numbers in the list
|| It now contains 0,1,2,3,4,5,6,7,8,9
*/
for (int i = 0; i < 10; ++i) list1.push_back(i);
list1.pop_front(); // erase the first element 0
list1.pop_back(); // erase the last element 9
list1.erase(list1.begin()); // erase the first element (1) using an iterator
list1.erase(list1.begin(), list1.end()); // erase all the remaining elements
cout << "list contains " << list1.size() << " elements" << endl;
}
输出是:
list contains 0 elements
15 用list成员函数remove()从list中删除元素。
list的成员函数remove()用来从list中删除元素。
/*
|| Using the list member function remove to remove elements
*/
#include <string>
#include <list>
#include <algorithm>
#include<iostream>
using namespace std;
PrintIt (const string& StringToPrint) {
cout << StringToPrint << endl;
}
void main (void) {
list<string> Birds;
Birds.push_back("cockatoo");
Birds.push_back("galah");
Birds.push_back("cockatoo");
Birds.push_back("rosella");
Birds.push_back("corella");
cout << "Original list with cockatoos" << endl;
for_each(Birds.begin
|