STL list介绍

1:定义一个list

#include <string>
#include <list>
int main (void) {
  list<string> Milkshakes;
}

2:使用list的成员函数push_back和push_front插入一个元素到list中

#include <string>
#include <list>

int main (void) {
  list<string> Milkshakes;
  Milkshakes.push_back("Chocolate");//把一个对象放到一个list的后面
  Milkshakes.push_back("Strawberry");//把一个对象放到一个list的后面
  Milkshakes.push_front("Lime");//把一个对象放到一个list的前面
  Milkshakes.push_front("Vanilla");//把一个对象放到一个list的前面
}

3:使用list的成员函数empty()判断list是否为空

if (Milkshakes.empty())
{
 printf(“this list is empty”);
}

4:用list< string>::iterator得到指向list的指针

 list<string> Milkshakes;
liststring>::iterator MilkshakeIterator;
for(MilkshakeIterator= Milkshakes.Begin();MilkshakeIterator!= Milkshakes.end();MilkshakeIterator++)
{
 printf(“%s”, *MilkshakeIterator);
} //输出list中的所有对象

说明:Milkshakes.Begin()和Milkshakes.end()函数返回指向list< string>::iterator的指针,由于list采用链表结构,因此它不支持随机存取,因此不能用Milkshakes.begin()+3来指向list中的第四个对象,vector和deque支持随机存取。

5: 用STL的通用算法count()来统计list中的元素个数

#include <list>
#include <algorithm>

int main (void) {
  list<int> 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 " << NumberOf100Scores << " scores of 100" << endl;
}
//程序的输出: There were 2 scores of 100

6:用STL的通用算法count_if()来统计list中的元素个数
count_if()是count()的一个更有趣的版本。他采用了STL的一个新组件,函数对象。count_if() 带一个函数对象的参数。函数对象是一个至少带有一个operator()方法的类。有些STL算法作为参数接收 函数对象并调用这个函数对象的operator()方法。 函数对象被约定为STL算法调用operator时返回true或false。

//举个例子:我们将数一数牙刷的销售数量。   
 #include <string>
#include <list>
#include <algorithm>

const string ToothbrushCode("0003");

class IsAToothbrush {
public:  
bool operator() ( string& SalesRecord ) {
    return SalesRecord.substr(0,4)==ToothbrushCode;
  }     
};

int main (void) {
  list<string> SalesRecords;

  SalesRecords.push_back("0001 Soap");
  SalesRecords.push_back("0002 Shampoo");
  SalesRecords.push_back("0003 Toothbrush");
  SalesRecords.push_back("0004 Toothpaste");
  SalesRecords.push_back("0003 Toothbrush");

  int NumberOfToothbrushes(0);  
  count_if (SalesRecords.begin(), SalesRecords.end(), 
             IsAToothbrush(), NumberOfToothbrushes);

  cout << "There were " 
       << NumberOfToothbrushes 
       << " toothbrushes sold" << endl;
}
//这是这个程序的输出: There were 2 toothbrushes sold   

注: 这个程序是这样工作的:
(1)定义一个函数对象类IsAToothbrush,这个类的对象能判断卖出的是否是牙刷 。
(2)如果这个记录是卖出牙刷的记录的话,函数调用operator()返回一个true,否则返回false。
(3)count_if()算法由第一和第二两个iterator参数指出的范围来处理容器对象。它将对每个 IsAToothbrush()返回true的容器中的对象增加
NumberOfToothbrushes的值。
(4)最后的结果是NumberOfToothbrushes这个变量保存了产品代码域为”0003”的记录的个数,也就是牙刷的个数。

7:使用STL通用算法find()在list中查找对象

#include <string> 
#include <list> 
#include <algorithm> 
# 
int main (void) { 
  list<string> Fruit; 
  list<string>::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" << endl; 
  } 
  else { 
   cout << *FruitIterator << endl; 
  } 
} 

//输出是: Pineapple 

如果没有找到指出的对象,就会返回Fruit.end()的值,要是找到了就返回一个指着找到的对象的iterator

8:使用STL通用算法find_if()在list中搜索对象
这是find()的一个更强大的版本。这个例子演示了find_if(),它接收一个函数对象的参数作为参数, 并使用它来做更复杂的评价对象是否和给出的查找条件相付。
假设我们的list中有一些按年代排列的包含了事件和日期的记录。我们希望找出发生在1997年的事件。

#include <string>
#include <list>
#include <algorithm>

class EventIsIn1997 {
public:
 bool operator () (string& EventRecord) {
   // 返回子串     
   return EventRecord.substr(12,4)=="1997";
  }  
};

int main (void) {
  list<string> Events;
     //年的起始位置相同
  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<string>::iterator EventIterator = find_if (Events.begin(), Events.end(), EventIsIn1997());

  if (EventIterator==Events.end()) {  
    cout << "Event not found in list" << endl; 
  }
  else {
   cout << *EventIterator << endl;
  }
}
//程序输出: 10 January  1997  Client agrees to job(找到第一个就返回)

9:使用list的成员函数sort()排序一个list。

#include <string>
#include <list>
#include <algorithm>

PrintIt (string& StringToPrint) { cout << StringToPrint << endl;}

int main (void) {
  list<string> Staff;
  list<string>::iterator PeopleIterator;

  Staff.push_back("John");
  Staff.push_back("Bill");
  Staff.push_back("Tony");
  Staff.push_back("Fidel");
  Staff.push_back("Nelson"); 

  cout << "The unsorted list " << endl;
  for_each(Staff.begin(), Staff.end(), PrintIt );

  Staff.sort();

  cout << "The sorted list " << endl;
  for_each(Staff.begin(), Staff.end(), PrintIt); 
}

输出是:

The unsorted list
John
Bill
Tony
Fidel
Nelson
The sorted list
Bill
Fidel
John
Nelson
Tony

10:使用list的成员函数insert插入一个对象到list中

#include <list>

int main (void) {
  list<int> list1;
   //0,1,2,3,4,5,6,7,8,9
  for (int i = 0; i < 10; ++i)  list1.push_back(i);   

  // -1,0,1,2,3,4,5,6,7,8,9
  list1.insert(list1.begin(), -1); 

  //-1,0,1,2,3,4,5,6,7,8,9,10
  list1.insert(list1.end(), 10);

  //-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]);
}

注:insert()函数把一个或若干个元素插入到你指出的iterator的位置。你的元素将出现在 iterator指出的位置以前。

11:如何在list中删除元素

cList.pop_front(); //删除第一个元素
cList.pop_back(); //删除最后一个元素
cList. Erase(cList.begin()); //使用iterator删除第一个元素;
cList. Erase(cList.begin(), cList.End()); //使用iterator删除所有元素;
cList.remove(‘c’); //使用remove函数删除指定的对象;

//删除所有的’c’ ,并返回指向新的list的结尾的iterator
list<char>::iterator newEnd;
newEnd = cList.remove(cList.begin(), cList.end(), ‘c’);   

12:程序示例

#include <cstdlib>
#include <iostream>
#include <list>
using namespace std;
int main(int argc, char *argv[])
{
    list<double> l;  
    cout<<"l size: "<<l.size()<<endl; 
    for(int i=0; i<5; i++)
    {
        l.push_back((i + 1) / 1000.0);
    }
    cout<<"l size: "<<l.size()<<endl; 
    list<double>::iterator current = l.begin(); 
    cout<<"Elements in l:"<<endl;
    while( current != l.end() )
    {
        cout<<*current<<endl;
        current++;
    }  
    current = l.begin(); 
    current++;
    current++;
    l.insert(current, 0.1);
    cout<<"Elements in l:"<<endl;
    for(list<double>::iterator p = l.begin(); p != l.end(); p++)
    {
        cout<<*p<<endl;
    } 
}
STL list是C++标准模板库中的一个双向链表容器,它提供了一系列接口用于操作和管理链表中的元素。下面是一些常见的STL list接口: 1. 构造函数: - list(size_type n, const value_type& val = value_type()):构造包含n个值为val的元素的list。 - list():构造一个空的list。 - list(const list& x):拷贝构造函数,用于复制另一个list的内容构造新的list。 - list(InputIterator first, InputIterator last):用[first, last)区间中的元素构造list。 2. 容器大小: - size():返回list中元素的个数。 - empty():检查list是否为空。 3. 元素访问: - front():返回list中第一个元素的引用。 - back():返回list中最后一个元素的引用。 4. 插入和删除元素: - push_front(const value_type& val):在list的开头插入一个元素。 - pop_front():移除list的第一个元素。 - push_back(const value_type& val):在list的末尾插入一个元素。 - pop_back():移除list的最后一个元素。 - insert(iterator position, const value_type& val):在指定位置之前插入一个元素。 - erase(iterator position):移除指定位置的元素。 - erase(iterator first, iterator last):移除[first, last)区间中的元素。 5. 元素操作: - clear():移除list中的所有元素。 - remove(const value_type& val):移除所有等于val的元素。 - unique():移除所有相邻重复的元素。 - sort():对list中的元素进行排序。 - reverse():反转list中元素的顺序。 你可以参考C++官方文档(https://cplusplus.com/reference/list/list/)了解更多关于STL list的接口和用法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员的资料库

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值