小结STL之std::list

list是C++标准模版库(STL,Standard Template Library)中的部分内容。实际上,list容器就是一个双向链表,可以高效地进行插入删除元素。

使用list容器之前必须加上STL的list容器的头文件:#include<list>

list属于stl所以使用前要加 using std::list; (或者直接全局:using namespace std;)


Member functions

(constructor)Construct list (public member function )//constructor
(destructor)List destructor (public member function )//destructior
operator=Assign content (public member function )//赋值运算符

Iterators:

beginReturn iterator to beginning (public member function
)//第一个元素的迭代器,正序
endReturn iterator to end (public member function
)//最后一个元素的迭代器在,正序
rbeginReturn reverse iterator to reverse beginning (public member function
)//最后一个元素的迭代器,倒序
rendReturn reverse iterator to reverse end (public member function
)//第一个元素的迭代器,倒序
cbegin Return const_iterator to beginning (public member function
)
cend Return const_iterator to end (public member function
)
crbegin Return const_reverse_iterator to reverse beginning (public member function
)
crend Return const_reverse_iterator to reverse end (public member function
)

Capacity:

emptyTest whether container is empty (public member function
)//返回是否为空
sizeReturn size (public member function
)//返回当前大小
max_sizeReturn maximum size (public member function
)//返回最大大小

Element access:

frontAccess first element (public member function
)//返回第一个元素
backAccess last element (public member function
)//返回最后一个元素

Modifiers:

assignAssign new content to container (public member function
)
emplace_front Construct and insert element at beginning (public member function
)
push_frontInsert element at beginning (public member function
)
pop_frontDelete first element (public member function
)
emplace_back Construct and insert element at the end (public member function
)
push_backAdd element at the end (public member function
)
pop_backDelete last element (public member function
)
emplace Construct and insert element (public member function
)//构造并插入
insertInsert elements (public member function
)//向list中插入某个元素
eraseErase elements (public member function
)//删除某个元素
swapSwap content (public member function
)//交换一个列表的两个元素
resizeChange size (public member function
)//重新设定大小
clearClear content (public member function
)//清空

Operations:

spliceTransfer elements from list to list (public member function
)//移动(从一个list到另一个list)
removeRemove elements with specific value (public member function
)//去除特定值的元素
remove_ifRemove elements fulfilling condition (public member function template
)//去除符合条件的元素
uniqueRemove duplicate values (public member function
)//去除重复元素
mergeMerge sorted lists (public member function
)//合并
sortSort elements in container (public member function
)//排序
reverseReverse the order of elements (public member function
)//反转

Observers:

get_allocatorGet allocator (public member function
)

Non-member function overloads

relational operators (list) Relational operators for list (function
)
swap (list)  Exchanges the contents of two lists (function template
)  //交换两个列表

下面对几个常用的操作举例:

1.构建及初始化

// 创建实例以及赋值
#include <iostream>
#include <list>
using namespace std;
int main () {
    //第一种,通过构造函数
    int myints[] = {75,23,65,42,13};
    list<int> mylist1(myints, myints+5);
    list<int> mylist2(2,100);         // 2个值为100的元素
    //第二种,用push_back,或push_front
    for (int i = 1; i <= 5; ++i) mylist1.push_back(i);
    mylist2.push_front (200);
    mylist2.push_front (300);
    //第三种,用assign
    list<int> first;
    list<int> second;
    first.assign(7,100);                       // 给first添加7个值为100的元素
    second.assign(first.begin(), first.end()); // 复制first给second
    int myints[] = {16, 8, 4};
    first.assign (myints, myints + 3);         // 将数组myints的内容添加给first

    //第四种,见insert函数
    return 0;
}

2.迭代器的创建及使用迭代器遍历

//list的遍历
#include <iostream>
#include <list>
using namespace std;
int main () {
    int myints[] = {75,23,65,42,13};
    list<int> mylist (myints,myints+5);
    cout << "mylist contains:";
    //这是正序输出:
    for (list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;
    //使用c++11和c++14的新特性auto更加方便准确
    auto it = mylist.begin();

    list.clear();
    //逆序输出:
    for (int i = 1; i <= 5; ++i) mylist.push_back(i);
    cout << "mylist backwards:";
    for (list<int>::reverse_iterator rit = mylist.rbegin(); rit != mylist.rend(); ++rit)
        cout << ‘ ‘ << *rit;
    cout << ‘\n‘;
    return 0;
}

输出结果为:
mylist contains: 75 23 65 42 13
mylist backwards: 5 4 3 2 1

3.获取列表信息

  

// list::assign
#include <iostream>
#include <list>
using namespace std;
int main () {
    list<int> first;
    list<int> second;
    first.assign(7,100);                      // 给first添加7个值为100的元素
    second.assign(first.begin(), first.end()); // 复制first给second

    int myints[] = {16, 8, 4};
    first.assign (myints, myints + 3);            // 将数组myints的内容添加给first

    cout << "Size of first: " << int (first.size()) << ‘\n‘;
    cout << "Size of second: " << int (second.size()) << ‘\n‘;
    return 0;
}
输出结果为:
Size of first: 3
Size of second: 7

  2.push和pop添加元素

    因为list是双向的所有总共有push_front ,push_back ,pop_front,po_back四种

#include <iostream>
#include <list>
using namespace std;
int main () {
    list<int> mylist (2,100);         // 2个值为100的元素
    // list::push_front
    mylist.push_front (200);
    mylist.push_front (300);

    cout << "mylist contains:";
    for (list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    // list::pop_front
    cout << "Popping out the elements in mylist:";
    while (!mylist.empty()) {
        cout << ‘ ‘ << mylist.front();
        mylist.pop_front();
    }
    cout << "\nFinal size of mylist is " << mylist.size() << ‘\n‘;

    // list::push_back
    int myint;
    cout << "Please enter some integers (enter 0 to end):\n";
    do {
        cin >> myint;
        mylist.push_back (myint);
    } while (myint);
    cout << "mylist contains:";
    for (list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    // list::pop_back
    while (!mylist.empty()) {
        cout << ‘ ‘ <<  mylist.back();
        mylist.pop_back();
    }
    cout << "\nFinal size of mylist is " << mylist.size() << ‘\n‘;

    return 0;
}
输出结果:
mylist contai: 300 200 100 100
Popping out the elements in mylist: 300 200 100 100
Final size of mylist is 0
Please enter some integers (enter 0 to end):
23 8 5 6 0
mylist contains: 56 23 8 5 6 0
6 5 8 23 56
Final size of mylist is 0

  3.insert插入新元素

// inserting into a list
#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main () {
    list<int> mylist;
    list<int>::iterator it;
    // 初始化
    for (int i = 1; i <= 5; ++i) mylist.push_back(i); // 1 2 3 4 5
    it = mylist.begin();
    ++it;       // 迭代器it现在指向数字2                      ^
    //在i0t指向的位置出插入元素10
    mylist.insert (it,10);                        // 1 10 2 3 4 5

    // "it" 仍然指向数字2                                   ^
    //在it指向的位置出插入两个元素20
    mylist.insert (it,2,20);                      // 1 10 20 20 2 3 4 5

    --it;       // 现在it指向数字20                             ^

    vector<int> myvector (2,30); //创建vector容器,并初始化为含有2个值为30的元素
    //将vector容器的值插入list中
    mylist.insert (it,myvector.begin(),myvector.end());
                                                // 1 10 20 30 30 20 2 3 4 5
    //it仍然指向数字20                            //               ^
    cout << "mylist contains:";
    for (it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    return 0;
}
输出结果:
mylist contains: 1 10 20 30 30 20 2 3 4 5

  4.erases删除元素

// erasing from list
#include <iostream>
#include <list>
using namespace std;
int main () {
    list<int> mylist;
    list<int>::iterator it1,it2;

    // set some values:
    for (int i = 1; i < 10; ++i) mylist.push_back(i*10);

                                // 10 20 30 40 50 60 70 80 90
    it1 = it2 = mylist.begin(); // ^^
    advance (it2,6);            // ^                 ^
    ++it1;                      //    ^              ^

    it1 = mylist.erase (it1);   // 10 30 40 50 60 70 80 90
                                //    ^           ^

    it2 = mylist.erase (it2);   // 10 30 40 50 60 80 90
                                //    ^           ^

    ++it1;                      //       ^        ^
    --it2;                      //       ^     ^
    //没有变量接收其返回值
    mylist.erase (it1,it2);     // 10 30 60 80 90
                                //       ^
    cout << "*it1 : " << *it1 << endl;
    cout << "mylist contains:";
    for (it1 = mylist.begin(); it1 != mylist.end(); ++it1)
        cout << ‘ ‘ << *it1;
    cout << ‘\n‘;

  return 0;
}
输出结果:
it1 : 40
mylist contains: 10 30 60 80 90

  5.clear() 清空

5.对列表的一些操作

  1.unique  删除重复值

// list::unique
#include <iostream>
#include <cmath>
#include <list>
using namespace std;
// a binary predicate implemented as a function:
bool same_integral_part (double first, double second) { return ( int(first)==int(second) ); }

// a binary predicate implemented as a class:
struct is_near {
    bool operator() (double first, double second) { return (fabs(first-second)<5.0); }
};

int main () {
    double mydoubles[] = { 12.15, 2.72, 73.0, 12.77, 3.14,
                       12.77, 73.35, 72.25, 15.3, 72.25 };
    list<double> mylist (mydoubles,mydoubles+10);
    cout << "mylist contains:";
    for (list<double>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    mylist.unique();
    cout << "mylist contains:";
    for (list<double>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    mylist.sort();             //  2.72,  3.14, 12.15, 12.77, 12.77,
                             // 15.3,  72.25, 72.25, 73.0,  73.35

    mylist.unique();           //  2.72,  3.14, 12.15, 12.77
                             // 15.3,  72.25, 73.0,  73.35
    cout << "mylist contains:";
    for (list<double>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    mylist.unique (same_integral_part);  //  2.72,  3.14, 12.15
                                       // 15.3,  72.25, 73.0
    cout << "mylist contains:";
    for (list<double>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    mylist.unique (is_near());           //  2.72, 12.15, 72.25

    cout << "mylist contains:";
    for (list<double>::iterator it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

  return 0;
}
输出结果:
mylist contains: 12.15 2.72 73 12.77 3.14 12.77 73.35 72.25 15.3 72.25
mylist contains: 12.15 2.72 73 12.77 3.14 12.77 73.35 72.25 15.3 72.25
mylist contains: 2.72 3.14 12.15 12.77 15.3 72.25 73 73.35
mylist contains: 2.72 3.14 12.15 15.3 72.25 73
mylist contains: 2.72 12.15 72.25

  2.sort 排序

    void sort();//默认升序

    void sort(bool cmp);//按照自定的cmp函数的true值排列

    对于自定的类型还可以在共有函数中重载“<”运算符进行定义

// list::sort
#include <iostream>
#include <list>
#include <string>
#include <cctype>
using namespace std;
// comparison, not case sensitive.
bool compare_nocase (const string& first, const string& second) {
    unsigned int i = 0;
    while ((i < first.length()) && (i < second.length()) ) {
        //将大写字母转为小写字母
        if (tolower(first[i]) < tolower(second[i])) return true;
        else if (tolower(first[i]) > tolower(second[i])) return false;
        ++i;
    }
    return ( first.length() < second.length() );
}

int main () {
    list<string> mylist;
    list<string>::iterator it;
    mylist.push_back ("one");
    mylist.push_back ("two");
    mylist.push_back ("Three");

    mylist.sort();

    cout << "mylist contains:";
    for (it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

    mylist.sort(compare_nocase);

    cout << "mylist contains:";
    for (it = mylist.begin(); it != mylist.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

  return 0;
}
输出结果:
mylist contains: Three one two
mylist contains: one Three two

  3.merge 合并两个有序列表

    注意:一定是有序才可以,不然在合并前要先sort()

// list::merge
#include <iostream>
#include <list>
using namespace std;
// compare only integral part:
bool mycomparison (double first, double second) { return ( (first)<(second) ); }

int main () {
    list<double> first, second;

    first.push_back (3.1);
    first.push_back (2.2);
    first.push_back (2.9);

    second.push_back (3.7);
    second.push_back (7.1);
    second.push_back (1.4);

    first.sort();
    second.sort();

    first.merge(second);
    cout << "first contains:";
    for (list<double>::iterator it = first.begin(); it != first.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;
    // (second 现在为空)

    second.push_back (2.1);
    second.push_back(2.5);

    first.merge(second,mycomparison);
    cout << "first contains:";
    for (list<double>::iterator it = first.begin(); it != first.end(); ++it)
        cout << ‘ ‘ << *it;
    cout << ‘\n‘;

  return 0;
}
输出结果:
first contains: 1.4 2.2 2.9 3.1 3.7 7.1
first contains: 1.4 2.1 2.2 2.5 2.9 3.1 3.7 7.1

Member functions

(constructor)
Construct list (public member function
)
(destructor)
List destructor (public member function
)
operator=
Assign content (public member function
)

Iterators:

begin
Return iterator to beginning (public member function
)
end
Return iterator to end (public member function
)
rbegin
Return reverse iterator to reverse beginning (public member function
)
rend
Return reverse iterator to reverse end (public member function
)
cbegin
Return const_iterator to beginning (public member function
)
cend
Return const_iterator to end (public member function
)
crbegin
Return const_reverse_iterator to reverse beginning (public member function
)
crend
Return const_reverse_iterator to reverse end (public member function
)

Capacity:

empty
Test whether container is empty (public member function
)
size
Return size (public member function
)
max_size
Return maximum size (public member function
)

Element access:

front
Access first element (public member function
)
back
Access last element (public member function
)

Modifiers:

assign
Assign new content to container (public member function
)
emplace_front
Construct and insert element at beginning (public member function
)
push_front
Insert element at beginning (public member function
)
pop_front
Delete first element (public member function
)
emplace_back
Construct and insert element at the end (public member function
)
push_back
Add element at the end (public member function
)
pop_back
Delete last element (public member function
)
emplace
Construct and insert element (public member function
)
insert
Insert elements (public member function
)
erase
Erase elements (public member function
)
swap
Swap content (public member function
)
resize
Change size (public member function
)
clear
Clear content (public member function
)

Operations:

splice
Transfer elements from list to list (public member function
)
remove
Remove elements with specific value (public member function
)
remove_if
Remove elements fulfilling condition (public member function template
)
unique
Remove duplicate values (public member function
)
merge
Merge sorted lists (public member function
)
sort
Sort elements in container (public member function
)
reverse
Reverse the order of elements (public member function
)

Observers:

get_allocator
Get allocator (public member function
)

Non-member function overloads

relational operators (list)
Relational operators for list (function
)
swap (list)
Exchanges the contents of two lists (function template
)

原文地址:https://www.cnblogs.com/zhanghengyu/p/10888920.html

时间: 2024-10-12 22:40:04

小结STL之std::list的相关文章

c++ stl algorithm: std::fill, std::fill_n

std::fill 在[first, last)范围内填充值 #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v; v.resize(10); std::fill(v.begin(), v.end(), 100); return 0; } std::fill_n 在[fist, fist + count)范围内填充值 #inclu

STL C++ std::bind操作例子,仿函数操作配合算法库操作

1.stl::bind 和std::mem_fun_ref系列的配合使用出现了问题,多参形式不知道如何组织.适配器的操作真心难受!!!只能迷迷糊糊地用着.要使用非质变算法时需要作用于容器时只能考虑lambda或者transfer操作.待续 // functor-adapter_p431.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <algorithm>//元素操作算法 #include <functiona

STL之std::set、std::map的lower_bound和upper_bound函数使用说明

由于在使用std::map时感觉lower_bound和upper_bound函数了解不多,这里整理并记录下相关用法及功能. STL的map.multimap.set.multiset都有三个比较特殊的函数,lower_bound.upper_bound.equal_range. 原型如下: iterator lower_bound (const value_type& val) const; iterator upper_bound (const value_type& val) con

stl之std::remove_copy

template <class InputIterator, class OutputIterator, class T> OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& val); 说明: Copies the elements in the range [first,last) to the range beginning at

c++ stl algorithm: std::find, std::find_if

td::find: 查找容器元素, find只能查找容器元素为<基本数据类型> [cpp]  view plain copy #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v; for (int i = 0; i < 10; ++i) v.push_back(i); std::vector<int>

八、C++ 标准模板库-STL概述

C++ 标准模板库-STL概述 一.基本概念 1.1 泛型程序设计 C++ 语言的核心优势之一就是便于软件的重用,重用在两个方面有体现: 面向对象的思想:继承和多态,标准类库 泛型程序设计(generic programming) 的思想: 模板机制,以及标准模板库 STL 简单地说就是使用模板的程序设计法.将一些常用的数据结构(比如链表,数组,二叉树)和算法(比如排序,查找)写成模板,以后则不论数据结构里放的是什么对象,算法针对什么样的对象,则都不必重新实现数据结构,重新编写算法. 标准模板库

C++标准模板库-STL库基本算法

原文链接:http://blog.csdn.net/wangfengwf/article/details/11580989#t9 16.4  STL库基本算法 标准C++STL库中算法组件为一个很重要的组成部分,该组件提供了大多数最常见的通用算法的实现,并且这些实现是经过很多测试试验并被公认在处理上是高效的.将这些最常见的算法通用化实现,最大的优势就是开发者在应用中不需要为具体的常见算法的实现而费神,只需要包含相应的头文件直接使用即可,不仅仅提高的软件开发的效率,同时还有助于软件重用性的提高.

std::sort 学习:一种递归分治方法

// std::sort 学习:一种递归分治方法 今天看了看 stl 的 std::sort 的代码,众所周知,这个函数是在快速排序递归太深的时候使用堆排序防止过度退化,但是今天说的不是这个.我们只看快速排序的部分. 我们一般实现快速排序大概是这样的(本王随意写了个用下标当参数的排序函数,领会意思即可). void quick_sort(int first, int last) // 某个数组的 [first, last) {  if ((last - first) > 1) {  int mi

测试std::sort 和std::qsort 的性能, 修改编译器栈大小

根据effective STL中Item 46 提到, C程序员很难接受C++的STL中std::sort(定义于头文件<algorithm>)竟然比C语言的std::qsort(定义与头文件<cstdlib>中)快了670%. 最后Scot Meyer建议我们我们要使用C++的std::sort函数. 我们知道qsort 实现的排序算法是快排, 但是std::sort 实现的排序算法并不知道, 有人说这得看是哪一个STL版本了. std::sort的大部分实现的是quick so