zoukankan      html  css  js  c++  java
  • C++ STL List

    这次的学习竟拖延了两周, 上周去了乌兰布统, 回来是牙疼,肚子疼, 腿也疼,md反正是没一个地方舒服

    还是写上一句自己喜欢的一句话: 耽误你的不是运气和机遇, 而是那数不清的犹豫和无奈。

    List

    Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.

    List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it.

    They are very similar to forward_list: The main difference being that forward_list objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.

    Compared to other base standard sequence containers (arrayvector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

    The main drawback of lists and forward_lists compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list, one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elements).

    翻译:列表是一个序列容器,它允许在序列中的任何地方进行持续时间插入和删除操作,并在两个方向上进行迭代。

    列表容器被实现为双链表;双链表可以存储它们包含在不同的和不相关的存储位置中的每一个元素。排序是由协会内部保存到一个链接的每个元素到它前面的元素的一个链接,以及一个与它后面的元素的链接。

    它们非常类似于向前列表:主要的区别在于,向前列表对象是单链表,因此它们可以

    Container constructors

    Syntax:

    #include <list>
    container();
    container(const container & c);
    container( size_type num, const TYPE& val = TYPE());
    container( input_iterator start, input_iterator end);
    ~container();

    The default list constructor takes no arguments, creates a new instance of that list.

    翻译: 默认list构造函数不需要参数, 创造一个新的示例。

    The second constructor is a default copy constructor that can be used to create a new list that is a copy of the given list c.

    翻译: 第二个构造函数是一个默认的复制构造函数, 它可以用来创造一个新的list 和它是给定list c的一个复制品。--》 这里指引用

    The third construcot creates a list with space for num objects. If val is specified, each of those objects will be given that value.For example, 

    the following code creates a vector consisting of five copies of the integer 42:

    翻译: 第三个构造函数创建一个关于数字空间对象的list。 如果val是指定的, 那每一个对象将会给定值。看例子, 下面代码创建一个vector 5 个整数42组成。

    vector<int> v1(5, 42);

    The last constructor creates a list that is initialized to contain the elements between start and end. For example:

    翻译: 最后一个构造函数创建一个初始话的list, 它包含一个开始和结束之间的元素, 看例子:

     // create a vector of random integers
     cout << "original vector: ";
     vector<int> v;
     for( int i = 0; i < 10; i++ ) {
       int num = (int) rand() % 10;
       cout << num << " ";
       v.push_back( num );
     }
     cout << endl;            
    
     // find the first element of v that is even
     vector<int>::iterator iter1 = v.begin();
     while( iter1 != v.end() && *iter1 % 2 != 0 ) {
       iter1++;
     }              
    
     // find the last element of v that is even
     vector<int>::iterator iter2 = v.end();
     do {
       iter2--;
     } while( iter2 != v.begin() && *iter2 % 2 != 0 );              
    
     cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;         
    
     cout << "new vector: ";
     vector<int> v2( iter1, iter2 );
     for( int i = 0; i < v2.size(); i++ ) {
       cout << v2[i] << " ";
     }
     cout << endl;    

    When run, this code displays the following output:

     original vector: 1 9 7 9 2 7 2 1 9 8
     first even number: 2, last even number: 8
     new vector: 2 7 2 1 9 

    All of these constructors run in linear time except  the first , whice runs in constant time.

    翻译: 所有这些构造函数运行都是线性时间,第一个除外,运行常数时间。

    The default destructor is called when the list should be destroyed.

    翻译:当列表应该被销毁时,会调用缺省析构函数。

    Container operatoors

    Syntax:

    #include <list>
    container operator=(const container& c2);
    bool operator==(const container& c1, const container& c2);
    bool operator!=(const container& c1, const container& c2);
    bool operator <(const container& c1, const container& c2);
    bool operator >(const container& c1, const container& c2);
    bool operator>=(const container& c1, const container& c2);
    bool operator<=(const container& c1, const container& c2);

    All of the c++ containers can be compared and with the standard comparison operators: ==, !=, <=, >=, <, > , and =. Performing a comparison or assigning

    ont list to another takes linear time.

    翻译: 所有c++容器可以与标准运算符进行比较和分配: ==, !=, <=, >=, <, > , and =。执行比较或将一个列表分配给另一个列表需要线性时间。

    Two lists are equal if:

    翻译: 如果两个list是相等的。

      1. Their size is the same, and 

      翻译: 他们的大小是一样的

      2. Each member in location i in one list is equal to the member in location i in the other list.

      翻译: 一个list里面的每一个成员等于另一个list里面的每个成员的位置。

    Comparisons among lists are done lexicographically.

    翻译:列表之间的比较是按字母顺序进行的

    std::list::assign 【分配】

    Syntax:

    #include <list>
    void assign( size_type num, const TYPE& val);
    void assign(input_iterator start, input_iterator end);

    The assign() function either gives the current list the values from start to end, or gives it num copies of val.

     翻译: assigin() 函数要么给定当前list的值从start到end, 要么给他的副本值

    This function will destroy the previous contents of the list.

     翻译: 这个函数将破坏列表之前的内容。

    For exmaple , the following code uses assign() to put 10 copies of the integer 42 into a vector:

     翻译:看例子, 下面代码使用assign() 输出10 个整数42的副本到vector

    vector<int> v;
    v.assign(10, 42);
    for(int i = 0; i < v.size(); i++){
        cout << v[i] << " ";
    }

    The above code displays the following output:

     42 42 42 42 42 42 42 42 42 42   

    The next example shows how assign() can ben used to copy one vector to another:

    int assign(){
       vector<int> v;
        v.assign(10, 42);
        for (int i = 0; i < v.size(); ++i) {
            cout << v[i] << " ";
        }
        cout << endl;
    
        vector<int> v1;
        for (int i = 0; i < 10; i++){
            v1.push_back(i);
        }
        vector<int> v2;
        v2.assign(v1.begin(), v1.end());
        for (int i = 0; i < v2.size(); i++){
            cout << v2[i] << " ";
        }
        cout << endl;
    int assign(){
        list<int> first;
        list<int> second;
    
        first.assign(7, 100);
        cout << "first data is :" ;
        for (list<int>::iterator it = first.begin(); it!= first.end(); it++) {
            cout << ' ' << *it;
        }
        cout << endl;
        second.assign(first.begin(), first.end());
    
        int myints[] = {1776, 7, 4};
        first.assign(myints, myints+3);
    
        cout << "Size of first: " << int(first.size()) << endl;
        cout << "Size of second: " << int(second.size()) << endl;
    
        cout << "first data is :" ;
        for (list<int>::iterator it = first.begin(); it!= first.end(); it++) {
            cout << ' ' << *it;
        }
        cout << endl;
    
        cout << "second data is :" ;
        for (list<int>::iterator it = second.begin(); it!= second.end(); it++) {
            cout << ' ' << *it;
        }
        cout << endl;
    
        return 0;
    }

    When run , the above code displya the following output:

    0 1 2 3 4 5 6 7 8 9

    std::list::begin

    Syntax:

          iterator begin() noexcept;
    const_iterator begin() const noexcept;

    Return iterator to beginning


    Return an iterator pointing to the first element in the list container.

    翻译: 返回一个迭代器指向list容器的第一个参数。

    Notice that, unlike member list::front, which returns a reference to the first element, this function returns a bidirectional iterator pointing to it.

    翻译: 请注意, 与成员list::front,它返回对第一个元素的引用,这个函数返回指向它的双向迭代器。

    If the container is empty, the returned iterator value shall not be dereferenced.

    翻译:如果容器是空的,则返回的迭代器值将不会被取消引用。

    Parameters


    none

    Return Value ---》 针对第二个

    const_iterator begin() const noexcept;

    An iterator to the beginning of the sequence container.

    翻译: 一个迭代器到序列容器的开始。

    If the list object is const-qualified, the function return a const_iterator . Otherwise, it returns an iterator.

    翻译:如果list对象是const合格的, 函数返回一个const迭代器, 除此以外, 它返回一个引用。

    Member types iterator and const_iterator are bidirectional iterator types (pointing to an element and to a const element, respectively).

    翻译:成员类型iterator和const_iterator是双向迭代器类型(分别指向元素和const元素)。

    Example


    int begin(){
        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 << endl;
    
        for(int i = 0; i < 5; ++i){
            cout << i << endl;
        }
    
        return 0;
    }

    Output


    mylist contains: 75 23 65 42 13

    std::list::back

    Syntax:


    reference back();
    const_reference back() const;

    The back() function returns a reference to the last element in the list.

    翻译: back()函数返回list最后一个元素的引用

    For example:


    int back(){
        list<int> mylist;
        mylist.push_back(10);
    
        while (mylist.back() != 0){
            mylist.push_back(mylist.back()-1);
        }
        cout << "mylist contains: ";
        for (list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it){
            cout << " " << *it;
        }
        cout << '
    ';
    
        return 0;
    }

    std::list::clear

    Syntax:


    #include <list>
    void clear();

    The function clear() deletes all of the elements in the list. clear() runs in linear time.

    翻译: clear函数清除list里面所有元素, clear() 运行线性时间。

    For example:


    int _clear(){
        list<int> mylist;
        list<int>::iterator it;
    
        mylist.push_back(100);
        mylist.push_back(200);
        mylist.push_back(300);
    
        cout << "mylist contains: ";
        for(it=mylist.begin();it != mylist.end(); it++){
            cout << ' ' << *it;
        }
        cout << endl;
    
        mylist.clear();
    
        mylist.push_back(1101);
        mylist.push_back(2202);
    
        cout << "mylist.contains: ";
        for (it = mylist.begin(); it != mylist.end(); it++){
            cout << ' ' << *it;
        }
        cout << endl;
        return 0;
    }

    Output:


    mylist contains:  100 200 300
    mylist.contains:  1101 2202

    std::list::empty

    Syntax:


    #include <list>
    bool empty() const;

    The empty() function returns true if the list has no elements, false otherwise.

     翻译: empty()函数返回true, 如果列表值为空, 其他情况返回otherwise

    For example , the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a list and display its contents in reverse order:

    翻译: 看例子, 下面代码使用empty()作为(c/c++关键字)停止条件, 同时循环清除一个列表并以相反的顺序显示其内容, 下面代码我改了, 没有按照原例子

    For exmaple:


    
    
    int _empty(){
    list<int> mylist;
    list<int>::iterator it;

    int sum(0);
    cout << "total: " << sum << endl;
    for (int i = 1; i <= 10; i++){
    mylist.push_back(i);
    }

    for (it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
    cout << "mylist.empty status is :" << mylist.empty() << endl;
    while (!mylist.empty()){
    cout << ' ' << mylist.front();
    sum += mylist.front();
    mylist.pop_front();
    }
    cout << endl;

    cout << "mylist.empty status is :" << mylist.empty() << endl;

    cout << "mylist size(): " << mylist.size() << endl;
    cout << "total: " << sum << endl;
    return 0;
    }
     

    std::list::end

    Syntax:


    #include <list>
    iterator end();
    const_iterator end() const;

    The end() function returns an iterator just past the end of the list.

    Note that before you can access the last element of the list using an iterator that you get from a call to end(),

    you'll have to decrement the iterator first.

    For example , the following code uses begin() and end() to iterator through all of the members of a vector:

    #include <iostream>
    #include <list>
    
    int main ()
    {
      int myints[] = {75,23,65,42,13};
      std::list<int> mylist (myints,myints+5);
    
      std::cout << "mylist contains:";
      for (std::list<int>::iterator it=mylist.begin() ; it != mylist.end(); ++it)
        std::cout << ' ' << *it;
    
      std::cout << '
    ';
    
      return 0;
    }

    std::list::erase

    Syntax:


    #include <list>
    iterator erase( iterator loc);
    iterator erase( iterator start, iterator end);

    The erase() function either deletes the element at location loc, or deletes the elements between start and end

    (includeing start but not including end). The return value is the element after the last element erased.

    The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists

    and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.

    int _erase(){
        std::list<int> mylist;
        std::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
                                    //        ^
    
        std::cout << "mylist contains:";
        for (it1=mylist.begin(); it1!=mylist.end(); ++it1)
            std::cout << ' ' << *it1;
        std::cout << '
    ';
    
        return 0;
    
    }

    output:

    mylist contains: 10 30 60 80 90

    std::list::front

    Syntax:


        reference front();
    const_reference front() const;

    Access first element

    Return a reference to the first element in the list container.

    翻译: 返回一个list容器里面第一个元素的引用

    unlike memeber list::begin, which returns an iterator to this same element, this function returns a direct reference.

    翻译: 与成员list :: begin不同,它返回一个迭代器到同一个元素,这个函数返回一个直接引用。

    Calling this function on an empty container causes undefined behavior.

    Parameters


    none

    Example


    int _front(){
        
        list<int> mylist;
        mylist.push_back(77);
        mylist.push_back(22);
    
        cout << "mylist.front() is now " << mylist.front() << '
    ';
        mylist.front() -= mylist.back();
        cout << "mylist.front() is now " << mylist.front() << '
    ';
    
        for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it ; cout << endl;
        
        return 0;
    }

    Output


    mylist.front() is now 77
    mylist.front() is now 55
     55 22

    std::list::insert

    Syntax:


    iterator insert (const_iterator position, const value_type& val);

    iterator insert (const_iteratro position, size_type n, const value_type& val);
    template <class InputIterator>
    iterator insert (const_iterator position, InputIterator first, InputIterator last);
    iterator insert (const_iterator position, value_type&& val);

    iterator insert (const_iterator position, initializer_list<value_type> il);

    Insert elements

    The container is extended by inserting new elements before the element at the specifled position.

    翻译: 容器通过扩展插入新的元素在元素指定位置之前。

    This effectively increases the list size by the amount of elements inserted.

    翻译: 这有效地增加了列表大小,增加了插入的元素数量。

    Unlike other standard sequence containers, list and forward_list objects are specifically designed to be effcient

    inserting and removing elements in any position, even in the middle of the sequence.

    翻译: 与其他标准序列容器不同, list和forward_list对象专门设计用于在任何位置高效插入和删除元素,即使在序列的中间也是如此。

    The arguments determine how many elements are inserted  and to which values they are initialized:

    翻译: 参数决定插入多少个元素,以及它们初始化的值:

    Parameters


    positin
    

      Position in the container where the new elements are inserted.

      iterator is a member type, defined as a bidirectional iterator type that points to elements.

      翻译:放置在容器中插入新元素的位置。 iterator是一个成员类型,定义为指向元素的双向迭代器类型。

    val

      value to be copied (or moved) to the inserted elements.

      Member type value_type is the type of the elements in the container, defined in list as an alisa of its first    template parameter(T).

      翻译:放置在容器中插入新元素的位置。 iterator是一个成员类型,定义为指向元素的双向迭代器类型。

    n
    

       Number of element to insert. Each elemetn is initialized to a copy of val.

      Member type size_type is an unsigned integral type.

      翻译:要插入的元素数。每个元素都初始化为val的副本。 成员类型size_type是无符号整数类型。

    first, last
    

       Iterators specifying a range of elements. Copies of the elements in the range[first, last] are inserted at   position( in the same order).

      Notice that the range includes all the elements between first and last , including the element pointed by first but not the one pointed by last.

      The function template argument InputIterator shall be an input iterator type that points to elements of a type from which value_type objects can be constructed.

      翻译:迭代器指定一系列的元素。在位置(以相同的顺序)中插入了范围内的元素的副本,最后一个)。
    注意,范围包括了第一个和最后一个元素之间的所有元素,包括首先指向的元素,而不是最后一个指向的元素。
    InputIterator的函数模板参数应该是一种输入迭代器类型,它指向可以构造valuetype对象的类型的元素。

    il
    

       An initializer_list object. Copies of these elements are inserted at position (in the same order).
      These objects are automatically constructed from initializer list declarators.
      Member type value_type is the type of the elements in the container, defined in list as an alias of its first    template parameter (T).

      翻译: 一个initializer_list对象。这些元素的副本被插入到位置(以相同的顺序)。
      这些对象是由初始化器列表声明符自动构造的。
      会员类型valuetype是容器中元素的类型,在列表中定义为它的第一个模板参数(T)的别名

    Example


    // 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 << '
    ';
    
      return 0;
    }

    Output


    mylist contains: 1 10 20 30 30 20 2 3 4 5

    std::list::max_size

    Syntax


    #include <list>
    size_type max_size() const;

    The max_size() function return the maximum number of element that the list can hold. The max_size() function should not be confused with the size() or (c++ Strings) capacity() functions , which return the number of elements currently in the list and the the number of elements that the list will be able to hold before more memeber will have to be allocated, respectively.

    翻译:maxsize()函数返回列表所能容纳的最大元素数量。maxsize()函数不应该与size()或(C++字符串)容量()函数相混淆,后者返回列表中当前元素的数量,以及在需要分配更多内存之前,列表将能够容纳的元素数量。

    Return value


    none

    Example


    None

    std::list::merge

    syntax


    void merge (list& x);
    void merge (list&& x);
    template <class Compare>
    void merge (list& x, Compare comp);
    template <class Cpmpare>
    void merge (list&& x, Compare comp);

    Merge sorted lists
    Merges x into the list by transferring all of its elements at their respective ordered positions into the container (both containers shall already be ordered).
    将x合并到列表中,将所有的元素都转移到容器中(两个容器都已被订购)。
    This effectively removes all the elements in x (which becomes empty), and inserts them into their ordered position within container (which expands in size by the number of elements transferred). The operation is performed without constructing nor destroying any element: they are transferred, no matter whether x is an lvalue or an rvalue, or whether the value_type supports move-construction or not.
    这有效地删除了x中的所有元素(它变成了空的),并将它们插入到容器内的有序位置(通过传输的元素数量来扩展)。操作是在不构造或破坏任何元素的情况下执行的:无论x是lvalue还是rvalue,还是valuetype是否支持移动构造,都是被转移的。
    The template versions with two parameters (2), have the same behavior, but take a specific predicate (comp) to perform the comparison operation between elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without considering its reflexiveness).
    带有两个参数(2)的模板版本具有相同的行为,但是使用特定的谓词(comp)来执行元素之间的比较操作。这种比较将会产生一个严格的元素的弱排序(例如一个一致的传递比较,不考虑它的自反性)。
    This function requires that the list containers have their elements already ordered by value (or by comp) before the call. For an alternative on unordered lists, see list::splice.
    此函数要求列表容器的元素在调用之前已按值(或通过comp)排序。有关无序列表的替代方法,请参阅list :: splice。
    Assuming such ordering, each element of x is inserted at the position that corresponds to its value according to the strict weak ordering defined by operator< or comp. The resulting order of equivalent elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and existing elements precede those equivalent inserted from x).
    假设这样的排序,x的每个元素都是根据操作符<或合成所定义的严格的弱序来插入对应于它的值的位置,因此等价元素的顺序是稳定的(例如相同的元素保留了它们在调用之前的相对顺序,而现有的元素则先于从x中插入的等价物)。
    The function does nothing if (&x == this).

    翻译: 如果(&x == this),该函数不执行任何操作

    Return value


    none

    Example


    bool mycomplarison(double first, double second){
        cout << first << " and " << second << endl;
        return (int(first)<int(second));
    }
    
    int _merge(){
        list<double> first, second;
    
        first.push_back(3.1);
        first.push_back(2.2);
        first.push_back(2.9); // 3.1 2.2 2.9
    
        second.push_back(3.7);
        second.push_back(7.1);
        second.push_back(1.4);
    
    //    first.sort(); // 2.2 2.9 3.1
    //    second.sort(); // 1.4 3.7 7.1
    
        first.merge(second); //  1.4 2.2 2.9 3.1 3.7 7.1
        for (list<double>::iterator it = first.begin(); it != first.end(); it++) cout << ' ' << *it;cout << endl;
    
        second.push_back(3.1); // 3.1 
    
        for (list<double>::iterator it = first.begin(); it != first.end(); it++) cout << ' ' << *it;cout << endl;
        for (list<double>::iterator it = second.begin(); it != second.end(); it++) cout << ' ' << *it;cout << endl;
    
        first.merge(second, mycomplarison);
    
        cout << "first contains: ";
        for (list<double>::iterator it = first.begin(); it != first.end(); it++) cout << ' ' << *it;cout << endl;
    
        return 0;
    }

    output


     3.1 2.2 2.9 3.7 7.1 1.4
     3.1 2.2 2.9 3.7 7.1 1.4
     3.1
    3.1 and 3.1
    3.1 and 2.2
    3.1 and 2.9
    3.1 and 3.7
    3.1 and 7.1
    first contains:  3.1 2.2 2.9 3.7 3.1 7.1 1.4

    如果取消sort注释呢? 结果怎么样?

     1.4 2.2 2.9 3.1 3.7 7.1
     1.4 2.2 2.9 3.1 3.7 7.1
     3.1
    3.1 and 1.4
    3.1 and 2.2
    3.1 and 2.9
    3.1 and 3.1
    3.1 and 3.7
    3.1 and 7.1
    first contains:  1.4 2.2 2.9 3.1 3.7 3.1 7.1

    因为mycomplarison函数会格式化传递进去的每一个值, first是谁, second什么值呢? 进行int()格式化以后进行对比, 决定value position

    std::list::pop_back

    Syntax


    #include <list>
    void pop_back();

    The pop_back() function removes the last elements of the list. pop_back() runs in constant time.

    翻译: pop_back() 函数y移除列表的最后一个函数, 运行常数时间。

    Return Value


    none

    Example


    int _push_back(){
        list<int> mylist;
        int sum(0);
    
        mylist.push_back(100);
        mylist.push_back(200);
        mylist.push_back(300);
    
        while (!mylist.empty()){
            sum += mylist.back();
            mylist.pop_back();
        }
    
        cout << "The elements of mylist summed " << sum << endl;
        return 0;
    }

    std::list::pop_front

    The function pop_front() removes the first element of the list.The pop_front() function runs in constant time.

    std::list::push_back --> 类似python的append

    Syntax


    #include <list>
    void push_back( const TYPE& val);

    The push_back() function appends val to end of the list.

    For example, the following code puts 10 integers into a list:

       list<int> the_list;
       for( int i = 0; i < 10; i++ )
         the_list.push_back( i ); 

    std::list::push_front

    The push_front() function inserts val at the beginning of list.

    push_front() runs in constant time.

    代码参考push_back

    std::list::rbegin

    Syntax


    #include <list>
    reverse_iterator rbegin() noexcept;
    const_reverse_iterator rbegin() cosnt noexcept;

    The rbegin() function returns a reverse_iterator to the end of the current list.

    翻译: rbegin() 函数返回一个当前list的末尾取反迭代器

    rbegin() runs in constant time.

    Example


    #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 << '
    ';
    
      return 0;
    }

    std::list::remove

    Syntax


    #include <list>
    void remove (const TYPE &val);

    Remove elements with specific value

    Removes from the containers all the elements compare equal the val. This call the destructor of these object and reduces the container size by the number of elements removed.

    翻译: 从容器中移除所有与val匹配相等的值。

    unlike member function list::erase , which erase elements by their position (using an iterator), this function (list::remove) removes elements by their value.

    翻译: 与成员函数list::erase 不同, 通过它们的位置消除元素, 这个函数remove通过值删除它们的元素

    A silmial function, list::remouve_if , exists, which allow for a conditon other than an equality comparison to determine whether an element is removed.

    翻译: 一个类似的函数, list::remove_if , 它允许除了相等的比较之外的其他条件来确定是否删除了一个元素。

    Return value


    none

    Example


    int _remove(){
        int myints[] = {17, 89, 7, 14, 89, 5};
    
        list<int> mylist (myints, myints+6); // 17, 89, 7, 14, 89, 5
        cout << "mylist contains before not remove a element: ";
    //    for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
        mylist.remove(89); // 17 7 14 5
        cout << "mylist contains after remove a element: ";
    //    for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
    
    
        return 0;
    }

    std::list::remove_if

    Syntax


    template <class Predicate>
      void remove_if (Predicate pred);

    Remove elements fulfilling condition
    Removes from the container all the elements for which Predicate pred returns true. This calls the destructor of these objects and reduces the container size by the number of elements removed.

    The function calls pred(*i) for each element (where i is an iterator to that element). Any of the elements in the list for which this returns true, are removed from the container.

    从容器中删除谓词pred返回true的所有要素。这就调用这些对象的析构函数,并通过删除的元素数量减少容器的大小。
    这个函数为每个元素调用pred(i)(我是该元素的迭代器)。列表中返回true的任何元素都是从容器中删除的。

    Parameters


    pred

      
      Unary predicate that, taking a value of the same type as those contained in the forward_list object, returns   true for those values to be removed from the container, and false for those remaining.
      This can either be a function pointer or a function object.

      翻译: 一元谓词,取与货代列表对象中包含的相同类型的值,返回正确的值,以便从集装箱中删除这些值,而  其余的值则为false。
      这可以是一个函数指针或一个函数对象。

    Return value


    none

    Example


    // a predicate implemented as a function:
    bool single_digit (const int& value) { return (value<10); }
    
    // a predicate implemented as a class:
    struct is_odd {
        bool operator() (const int& value) { return (value%2)==1; }
    };
    
    int _remove_if ()
    {
        int myints[]= {15,36,7,17,20,39,4,1};
        std::list<int> mylist (myints,myints+8);   // 15 36 7 17 20 39 4 1
    
        // mylist.remove_if (20); // error
        // 15 36 17 20 39
        mylist.remove_if (single_digit);           // 15 36 17 20 39
    
        mylist.remove_if (is_odd());               // 36 20
    
        std::cout << "mylist contains:";
        for (std::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
            std::cout << ' ' << *it;
        std::cout << '
    ';
    
        return 0;
    }

    std::list::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 << '
    ';
    
      return 0;
    }

    std::list::resize

    指定大小, 并指定填充内容, 没有默认用0填充

    Syntax


    void resize (size_type n);
    void resize (size_type n, const value_type& val);

    Parameters


    n
    New container size, expressed in number of elements.
    Member type size_type is an unsigned integral type.
    val
    Object whose content is copied to the added elements in case that n is greater than the current container size.
    If not specified, the default constructor is used instead.
    Member type value_type is the type of the elements in the container, defined in list as an alias of the first template parameter (T).

    Return Value


    none

    Example


    #include <iostream>
    #include <list>
    
    int main ()
    {
      std::list<int> mylist;
    
      // set some initial content:
      for (int i=1; i<10; ++i) mylist.push_back(i);
    
      mylist.resize(5);
      mylist.resize(8,100);
      mylist.resize(12);
    
      std::cout << "mylist contains:";
      for (std::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
        std::cout << ' ' << *it;
    
      std::cout << '
    ';
    
      return 0;
    }

    std::list::reverse

    Syntax


    #include <list>
    void reverse()

    The function reverse() reverses the list, and takes linear time.

    Parameters


    none

    Return Value


    none

    Example


    int _reverse(){
        list<int> mylist;
    
        for(int i = 1; i < 10; i++)mylist.push_back(i);
    
        mylist.reverse();
    
        cout << "mylist contains: ";
        for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
    
        return 0;
    }

    output:

    mylist contains:  9 8 7 6 5 4 3 2 1

    std::list::size

    Syntax


      #include <list>
      size_type size() const;

    The size() function returns the number of elements in the current list.

    #include <iostream>
    #include <list>
    
    int main ()
    {
      std::list<int> myints;
      std::cout << "0. size: " << myints.size() << '
    ';
    
      for (int i=0; i<10; i++) myints.push_back(i);
      std::cout << "1. size: " << myints.size() << '
    ';
    
      myints.insert (myints.begin(),10,100);
      std::cout << "2. size: " << myints.size() << '
    ';
    
      myints.pop_back();
      std::cout << "3. size: " << myints.size() << '
    ';
    
      return 0;
    }
    0. size: 0
    1. size: 10
    2. size: 20
    3. size: 19

    std::list::sort

    Syntax


    void sort();
    
    template <class Compare>
    void sort sort(Compare comp)

    Sort elements in container

    Sorts the elements in the list, altering their wothin the container.

    对列表中的元素进行排序,改变它们在容器中的位置。

    The sorting is performed by applying an algorithm that uses either operator to compare elements.This comparison shall produce a strict weak ordering of the elements.

    The resulting order of equivalent elements is stable:i.e., equivalent elements preserve the relative order they had before the call.

    The entire operation does not involve the construction, destruction or copy of any element object. Elements are moved the container.

    #include <iostream>
    #include <list>
    #include <string>
    #include <cctype>
    
    bool compare_nocase(const std::string& first, const std::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 _sort(){
        std::list<string> mylist;
        std::list<string>::iterator it;
        mylist.push_back("one");
        mylist.push_back("two");
        mylist.push_back("Three");
    
        for (it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
    
        mylist.sort();
    
        for (it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
    
        mylist.sort(compare_nocase);
    
        for (it = mylist.begin(); it != mylist.end(); it++) cout << ' ' << *it; cout << endl;
    
    
    }
    
    int test() {
    
        _sort();
    
        return 0;
    }

    output:

     one two Three
     Three one two
     one Three two

    For default strings, the comparison is a strict character code comparison, where all uppercase letters compare lower than all lowercase letters, putting all strings beginning by an uppercase letter before in the first sorting operation.
    对于默认字符串,比较是严格的字符代码比较,所有大写字母都比所有小写字母都要低,在第一个排序操作之前,所有的字符串都以大写字母开头。

    Using the function compare_nocase the comparison is made case insensitive.

    使用比较的函数比较是不敏感的。

    std::list::splice -->合并

    Syntax:


    #include <list>
    void splice( iterator pos, list& lst);     // entire list
    void splice( iterator pos, list&& lst);


    void splice(const_iterator position, list& x, const_iterator i); // single element(2)
    void splice(const_iterator position, list&& x, const_iterator i);

    void splice(const_iterator position, list& x, const_iterator first, const_iterator last); //element range(3)
    void splice(const_iterator position, list&& x, const_iterator first, const_iterator last);

    Transfer elements from list to list

    Transfers elements from x into the container, inserting them at position.

    将元素从x转移到容器中,将它们插入位置。

    This effectively inserts those elements into the container and remove them from x, altering the sizes of both containers. The operation does not involve the construction or destruction of any element. They are transferred, no matter whether x is an lvalue or an rvalue, or whether the value_type supports move-construction or not.

    这有效地将这些元素插入到容器中,并将它们从x中删除,从而改变了两个容器的大小。该操作不涉及任何元素的构造或销毁。它们被转移,不管x是lvalue还是rvalue,或者valuetype是否支持移动构造。

    The first version (1) transfers all the elements of x into the container.
    The second version (2) transfers only the element pointed by i from x into the container.
    The third version (3) transfers the range [first,last) from x into the container.

    第一个版本(1)将x的所有元素都传输到容器中。
    第二个版本(2)只将i从x指向容器的元素传输到容器中。
    第三个版本(3)将范围从x转移到容器中。

    Paremeters


    position
    Position within the container where the elements of x are inserted.
    Member types iterator and const_iterator are bidirectional iterator types that point to elements.
    x
    A list object of the same type (i.e., with the same template parameters, T and Alloc).
    This parameter may be *this if position points to an element not actually being spliced (for the first version, this is never the case, but for the other versions this is possible).
    i
    Iterator to an element in x. Only this single element is transferred.
    iterator is a member type, defined as a bidirectional iterator type.
    Member types iterator and const_iterator are bidirectional iterator types that point to elements.
    first,last
    Iterators specifying a range of elements in x. Transfers the elements in the range [first,last) to position.
    Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
    Member types iterator and const_iterator are bidirectional iterator types that point to elements.

    Return value


    none

    Example


    #include <iostream>
    #include <list>
    
    int main ()
    {
      std::list<int> mylist1, mylist2;
      std::list<int>::iterator it;
    
      // set some initial values:
      for (int i=1; i<=4; ++i)
         mylist1.push_back(i);      // mylist1: 1 2 3 4
    
      for (int i=1; i<=3; ++i)
         mylist2.push_back(i*10);   // mylist2: 10 20 30
    
      it = mylist1.begin();
      ++it;                         // points to 2
    
      mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
                                    // mylist2 (empty)
                                    // "it" still points to 2 (the 5th element)
                                              
      mylist2.splice (mylist2.begin(),mylist1, it);
                                    // mylist1: 1 10 20 30 3 4
                                    // mylist2: 2
                                    // "it" is now invalid.
      it = mylist1.begin();
      std::advance(it,3);           // "it" points now to 30
    
      mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
                                    // mylist1: 30 3 4 1 10 20
    
      std::cout << "mylist1 contains:";
      for (it=mylist1.begin(); it!=mylist1.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '
    ';
    
      std::cout << "mylist2 contains:";
      for (it=mylist2.begin(); it!=mylist2.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '
    ';
    
      return 0;
    }
    mylist1 contains: 30 3 4 1 10 20
    mylist2 contains: 2

    std::list::swap

    Syntax


    void swap (list& x);

    Exchanges the content of the container by the content of x, which is another list of the same type. Sizes may differ.
    用x的内容交换容器的内容,这是同一类型的另一个列表。大小可能不同。


    After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects.
    在对这个成员函数的调用之后,这个容器中的元素是在调用之前在x中的元素,而x的元素是在这个容器中的元素。所有迭代器、引用和指针对于交换的对象仍然有效。


    Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.
    请注意,非成员函数具有相同的名称、交换、重载该算法,并使用与此成员函数类似的优化。

    Whether the container allocators are also swapped is not defined, unless in the case the appropriate allocator trait indicates explicitly that they shall propagate.
    容器分配器是否也被交换没有定义,除非在这种情况下,适当的分配器特性明确表示它们将传播

    Parameters


    x
    Another list container of the same type as this (i.e., with the same template parameters, T and Alloc) whose content is swapped with that of this container.

    另一个与此相同类型的列表容器(例如有相同的模板参数T和Alloc),它们的内容与这个容器交换。

    Return value


    none

    Example


    int _swap(){
        list<int> first(3, 100);
        list<int> second(5, 200);
    
        first.swap(second);
    
        for (list<int>::iterator it = first.begin(); it != first.end(); it++) cout << ' ' << *it; cout << endl;
        for (list<int>::iterator it = second.begin(); it != second.end(); it++) cout << ' ' << *it; cout << endl;
    
    
        return 0;
    }

    output:

     200 200 200 200 200
     100 100 100
  • 相关阅读:
    pugixml
    C++ 头文件的理解
    图像的特征
    光圈与景深
    Unix高级环境编程
    用libtommath实现RSA算法
    【linux+C】神器 vim + 指针相关客串
    【算法25】对称子字符串的最大长度
    设计并实现同时支持多种视频格式的流媒体点播系统
    递归再一次让哥震惊了
  • 原文地址:https://www.cnblogs.com/renfanzi/p/9456205.html
Copyright © 2011-2022 走看看