#include
#include
#
int main (void) {
list Milkshakes;
Milkshakes.push_back(\"Chocolate\");
Milkshakes.push_back(\"Strawberry\");
Milkshakes.push_front(\"Lime\");
Milkshakes.push_front(\"Vanilla\");
}
We now have a list with four strings in it. The list member function push_back() places an object onto the back of the list. The list member function push_front() puts one on the front. I often push_back() some error messages onto a list, and then push_front() a title on the list so it prints before the error messages. 我们现在有个4个字符串在list中。list的成员函数push_back()把一个对象放到一个list的后面,而 push_front()把对象放到前面。我通常把一些错误信息push_back()到一个list中去,然后push_front()一个标题到list中,这样它就会在这个错误消息以前打印它了。
The list member function empty()list的成员函数empty()
知道一个list是否为空很重要。如果list为空,empty()这个成员函数返回真。我通常会这样使用它。通篇程序我都用push_back()来把错误消息放到list中去。然后,通过调用empty() 我就可以说出这个程序是否报告了错误。如果我定义了一个list来放信息,一个放警告,一个放严重错误,我就可以通过使用empty()轻易的说出到底有那种类型的错误发生了。
我可以整理这些list,然后在打印它们之前,用标题来整理它们,或者把它们排序成类。
这是我的意思:
/*
|| Using a list to track and report program messages and status
*/
#include
#include
#include
#
int main (void) {
#define OK 0
#define INFO 1
#define WARNING 2
#
int return_code;
#
list InfoMessages;
list<:string> WarningMessages;
#
// during a program these messages are loaded at various points
InfoMessages.push_back(\"Info: Program started\");
// do work...
WarningMessages.push_back(\"Warning: No Customer records have been found\");
// do work...
#
return_code = OK;
#
if (!InfoMessages.empty()) { // there were info messages
InfoMessages.push_front(\"Informational Messages:\");
// ... print the info messages list, we\"ll see how later
return_code = INFO;
}
#
if (!WarningMessages.empty()) { // there were warning messages
WarningMessages.push_front(\"Warning Messages:\");
// ... print the warning messages list, we\"ll see how later
return_code = WARNING;
}
#
// If there were no messages say so.
if (InfoMessages.empty() && WarningMessages.empty()) {
cout <<\"There were no messages \" <br>}
#
return return_code;
}
/*
|| How to print the contents of a simple STL list. Whew!
*/
#include
#include
#include
#
int main (void) {
list Milkshakes;
list::iterator MilkshakeIterator;
#
Milkshakes.push_back(\"Chocolate\");
Milkshakes.push_back(\"Strawberry\");
Milkshakes.push_front(\"Lime\");
Milkshakes.push_front(\"Vanilla\");
#
// print the milkshakes
Milkshakes.push_front(\"The Milkshake Menu\");
Milkshakes.push_back(\"*** Thats the end ***\");
for (MilkshakeIterator=Milkshakes.begin();
MilkshakeIterator!=Milkshakes.end();
++MilkshakeIterator) {
// dereference the iterator to get the element
cout <<*MilkshakeIterator <br>}
}
这个程序定义了一个iterator,MilkshakeIterator。我们把它指向了这个list的第一个元素。这可以调用Milkshakes.begin()来作到,它会返回一个指向list开头的iterator。然后我们把它和Milkshakes.end()的返回值来做比较,当我们到了那儿的时候就停下来。
容器的end()函数会返回一个指向容器的最后一个位置的iterator。当我们到了那里,就停止操作。我们不能不理容器的end()函数的返回值。我们仅知道它意味着已经处理到了这个容器的末尾,应该停止处理了。所有的STL容器都要这样做。
/*
|| How to count objects in an STL list
*/
#include
#include
#
int main (void) {
list Scores;
#
Scores.push_back(100); Scores.push_back(80);
Scores.push_back(45); Scores.push_back(75);
Scores.push_back(99); Scores.push_back(100);
#
int NumberOf100Scores(0);
count (Scores.begin(), Scores.end(), 100, NumberOf100Scores);
#
cout <<\"There were \" <<<\" scores of 100\" <br>}
The count() algorithm counts the number of objects equal to a certain value. In the above example it checks each integer object in a list against 100. It increments the variable NumberOf100Scores each time a container object equals 100. The output of the program is count()算法统计等于某个值的对象的个数。上面的例子它检查list中的每个整型对象是不是100。每次容器中的对象等于100,它就给NumberOf100Scores加1。这是程序的输出:
There were 2 scores of 100
/*
|| How to find things in an STL list
*/
#include
#include
#include
#
int main (void) {
list Fruit;
list::iterator FruitIterator;
#
Fruit.push_back(\"Apple\");
Fruit.push_back(\"Pineapple\");
Fruit.push_back(\"Star Apple\");
#
FruitIterator = find (Fruit.begin(), Fruit.end(), \"Pineapple\");
#
if (FruitIterator == Fruit.end()) {
cout <<\"Fruit not found in list\" <br>}
else {
cout <<*FruitIterator <br>}
}
/*
|| How to find things in an STL list MkII
*/
#include
#include
#include
#
class EventIsIn1997 {
public:
bool operator () (string& EventRecord) {
// year field is at position 12 for 4 characters in EventRecord
return EventRecord.substr(12,4)==\"1997\";
}
};
#
int main (void) {
list Events;
#
// string positions 0123456789012345678901234567890123456789012345
Events.push_back(\"07 January 1995 Draft plan of house prepared\");
Events.push_back(\"07 February 1996 Detailed plan of house prepared\");
Events.push_back(\"10 January 1997 Client agrees to job\");
Events.push_back(\"15 January 1997 Builder starts work on bedroom\");
Events.push_back(\"30 April 1997 Builder finishes work\");
#
list::iterator EventIterator =
find_if (Events.begin(), Events.end(), EventIsIn1997());
#
// find_if completes the first time EventIsIn1997()() returns true
// for any object. It returns an iterator to that object which we
// can dereference to get the object, or if EventIsIn1997()() never
// returned true, find_if returns end()
if (EventIterator==Events.end()) {
cout <<\"Event not found in list\" <br>}
else {
cout <<*EventIterator <br>}
}
这是程序的输出:
int NumberOfNullCharacters(0);
count(Characters.begin(), Characters.end(), \"\\0\", NumberOfNullCharacters);
cout <<\"We have \" <<br>让我们找字符\"1\"
list::iterator Iter;
Iter = find(Characters.begin(), Characters.end(), \"1\");
cout <<\"We found \" <<*Iter <br>这个例子演示了STL容器允许你以更标准的方法来处理空字符。现在让我们用STL的search算法来搜索容器中的两个null。
就象你猜的一样,STL通用算法search()用来搜索一个容器,但是是搜索一个元素串,不象find()和find_if() 只搜索单个的元素。
/*
|| How to use the search algorithm in an STL list
*/
#include
#include
#include
#
int main ( void ) {
#
list TargetCharacters;
list ListOfCharacters;
#
TargetCharacters.push_back(\"\\0\");
TargetCharacters.push_back(\"\\0\");
#
ListOfCharacters.push_back(\"1\");
ListOfCharacters.push_back(\"2\");
ListOfCharacters.push_back(\"\\0\");
ListOfCharacters.push_back(\"\\0\");
#
list::iterator PositionOfNulls =
search(ListOfCharacters.begin(), ListOfCharacters.end(),
TargetCharacters.begin(), TargetCharacters.end());
#
if (PositionOfNulls!=ListOfCharacters.end())
cout <<\"We found the nulls\" <br>}
The output of the program will be 这是程序的输出:
We found the nulls
search算法在一个序列中找另一个序列的第一次出现的位置。在这个例子里我们在ListOfCharacters中找TargetCharacters这个序列的第一次出现,TargetCharacters是包含两个null字符的序列。
search的参数是两个指着查找目标的iterator和两个指着搜索范围的iterators。因此我们我们在整个的ListOfCharacters的范围内查找TargetCharacters这个list的整个序列。
/*
|| Using insert to insert elements into a list.
*/
#include
#
int main (void) {
list list1;
#
/*
|| Put integers 0 to 9 in the list
*/
for (int i = 0; i<10; ++i) list1.push_back(i);
#
/*
|| Insert -1 using the insert member function
|| Our list will contain -1,0,1,2,3,4,5,6,7,8,9
*/
list1.insert(list1.begin(), -1);
#
/*
|| Insert an element at the end using insert
|| Our list 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
*/
}
注意,insert()函数把一个或若干个元素插入到你指出的iterator的位置。你的元素将出现在 iterator指出的位置以前。
List 构造函数
我们已经象这样定义了list:
list Fred;
你也可以象这样定义一个list,并同时初始化它的元素:
// define a list of 10 elements and initialise them all to 0
list Fred(10, 0);
// list now contains 0,0,0,0,0,0,0,0,0,0
或者你可以定义一个list并用另一个STL容器的一个范围来初始化它,这个STL容器不一定是一个list,仅仅需要是元素类型相同的的容器就可以。
vector Harry;
Harry.push_back(1);
Harry.push_back(2);
#
// define a list and initialise it with the elements in Harry
list Bill(Harry.begin(), Harry.end());
// Bill now contains 1,2
/*
|| Erasing objects from a list
*/
#include
#
int main (void) {
list 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 \" <<\" elements\" <br>}
输出是:
list contains 0 elements
/*
|| Using the list member function remove to remove elements
*/
#include
#include
#include
#
PrintIt (const string& StringToPrint) {
cout <<br>}
#
int main (void) {
list 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\" <br>for_each(Birds.begin(), Birds.end(), PrintIt);
#
Birds.remove(\"cockatoo\");
#
cout <<\"Now no cockatoos\" <br>for_each(Birds.begin(), Birds.end(), PrintIt);
}
输出是:
Original list with cockatoos
cockatoo
galah
cockatoo
rosella
corella
Now no cockatoos
galah
rosella
corella
/*
|| Using the generic remove algorithm to remove list elements
*/
#include
#include
#include
#
PrintIt(string& AString) { cout <<br>#
int main (void) {
list Birds;
list::iterator NewEnd;
#
Birds.push_back(\"cockatoo\");
Birds.push_back(\"galah\");
Birds.push_back(\"cockatoo\");
Birds.push_back(\"rosella\");
Birds.push_back(\"king parrot\");
#
cout <<\"Original list\" <br>for_each(Birds.begin(), Birds.end(), PrintIt);
#
NewEnd = remove(Birds.begin(), Birds.end(), \"cockatoo\");
#
cout <<<\"List according to new past the end iterator\" <br>for_each(Birds.begin(), NewEnd, PrintIt);
#
cout <<<\"Original list now. Care required!\" <br>for_each(Birds.begin(), Birds.end(), PrintIt);
}
The output will be
Original list
cockatoo
galah
cockatoo
rosella
king parrot
List according to new past the end iterator
galah
rosella
king parrot
Original list now. Care required!
galah
rosella
king parrot
rosella
king parrot
通用remove()算法返回一个指向新的list的结尾的iterator。从开始到这个新的结尾(不含新结尾元素)的范围包含了remove后剩下所有元素。你可以用list成员函数erase函数来删除从新结尾到老结尾的部分。
/*
|| Using the STL stable_partition algorithm
|| Takes any number of flags on the command line and
|| four filenames in order.
*/
#include
#include
#include
#
PrintIt ( string& AString ) { cout <<br>#
class IsAFlag {
public:
bool operator () (string& PossibleFlag) {
return PossibleFlag.substr(0,1)==\"-\";
}
};
#
class IsAFileName {
public:
bool operator () (string& StringToCheck) {
return !IsAFlag()(StringToCheck);
}
};
#
class IsHelpFlag {
public:
bool operator () (string& PossibleHelpFlag) {
return PossibleHelpFlag==\"-h\";
}
};
#
int main (int argc, char *argv[]) {
#
list CmdLineParameters; // the command line parameters
list::iterator StartOfFiles; // start of filenames
list Flags; // list of flags
list FileNames; // list of filenames
#
for (int i = 0; ibr>#
CmdLineParameters.pop_front(); // we don\"t want the program name
#
// make sure we have the four mandatory file names
int NumberOfFiles(0);
count_if(CmdLineParameters.begin(), CmdLineParameters.end(),
IsAFileName(), NumberOfFiles);
#
cout <<\"The \"
<<(NumberOfFi