C + + Standard Template Library STL implementation of the data structure of the linked list std::list analysis and use of __ garbled problem

Source: Internet
Author: User
Tags data structures sorted by name
Summary

This article mainly by the C + + Standard Template Library STL implementation of the data structure of the study and use to deepen the understanding of the data structure, that is, the relationship between the theoretical analysis of data structure and specific application implementation (STL), this article is the second series of summary, mainly for the linear table of the linked list STL : List for analysis and summary. Introduction

As a result of the previous time to Taiwan's large machine learning Cornerstone and skill courses were studied, found in the specific implementation of the various types of data structures often involved, such as linear tables, binary trees, graphs and so on, in the use of these data structures feel some difficulty, mainly to some basic data structure understanding enough, so taking advantage of the summer vacation, Recently some time will always be a moment to review the data structure, reference to the textbook is Wang Liju "c/s + + and data structure", in the specific application of the C + + Standard Template Library STL corresponding to the implementation of data structures, the main reference is the MSDN documentation. Follow the textbook step by step, now has reviewed the chain of chapters, the specific theory can refer to my blog: http://blog.csdn.net/lg1259156776/article/details/47018813

This attention point is used in the list template class. Body review of dynamic array classes

The previous summary of the STL vector dynamic Array class forgot to describe another dynamic array class deque that is very similar to the vector. This is supplemented by the following.

The STL Deque class needs to include <deque> and use of STD, which supports inserting or deleting elements at the beginning and end of an array, while vectors can only be inserted or deleted at the end, that is, only push_back and Pop_back. Deque allows you to insert and delete elements at the beginning using Push_front and Pop_front. The rest of the operations are roughly similar and no longer repeat.

Template <
   class Type, 
   class allocator=allocator<type> 
>
   class deque
<span style= "FONT-SIZE:18PX;" >//deque_push_front.cpp
//compile with:/EHsc
#include <deque>
#include <iostream>
#include <string>

int main () 
{
   using namespace std;
   Deque <int> C1;
   
   C1.push_front (1);
   if (c1.size ()!= 0)
      cout << "A:" << c1.front () << Endl;

   C1.push_front (2);
   if (c1.size ()!= 0)
      cout << "New-element:" << C1.front () << Endl;

Move initialize a deque of strings
   deque <string> C2;
   String Str ("a");

   C2.push_front (Move (str));
   cout << "moved:" << c2.front () << Endl;
} </span>
Summary: When you don't know how many elements you need to store, be sure to use a dynamic array of vectors or deque, and remember that vectors can only be push_back at one end, and deque can use Push_back and Push_front to expand at both ends. Also, when you access a dynamic array, do not cross its bounds.

list template class

The Standard Template Library provides a two-way list of std::list to programmers in the form of template classes. The main advantage of a two-way list is that it is quick to insert and delete elements, and the time is fixed, unlike sequential tables that require moving elements. From C + + 11, you can also use one-way linked list std::forward_list, only traversing in one direction.

Template <
   class Type, 
   class allocator=allocator<type> 
>
class List

the characteristics of the list

A list is a series of nodes in which each node contains a pointer to the next or previous node in addition to the object or data, and the STL implementation of the lists class allows elements to be inserted at the beginning, end, and middle, and the time required is fixed. Include <list> and STD when used. basic operation of list instantiation of

List<int> listintegers; List<float> listfloats and so on. To declare an iterator that points to elements in a list, you can do the following:

List<int>:: Const_iterator ielementinset; Remember Const_iterator, in the previous vector analysis, pointing to a read-only element, you can use iterator if you want to modify the contents of the container. There are some of the same as the vector of initialization operations, you can refer to the previous blog, later on the STL container for programming or interpretation, the instantiation of the same way, this pattern will appear for a long time, follow-up blog will not be more mention. Insert or delete an element at the beginning or end of a list

Similar to the Deque class, the Push_front/pop_front and Push_back/pop_back methods are used. Insert or delete an element in the middle of a list

One of the features of the list, which says that the time required to insert or delete elements in the middle is fixed, using the function insert () and erase ().

From the above analysis, basically all of the container class (Vector,list,deque ... The method patterns used are similar, which is helpful for analogy learning. the reversal and sorting of list elements

A unique feature of the list is that the iterator that points to elements is still valid after the elements of the list are rearranged or inserted, and for this to happen, List provides the member methods sort and reverse, although the STL also provides both algorithms (in the algorithm class <algorithm >), and these algorithms can also be used on the list class. use reverse () to reverse the order of elements

List provides member function reverse with no parameters, and function is to reverse the order of elements in the list:

<span style= "FONT-SIZE:18PX;" >//list_reverse.cpp
//compile with:/EHsc
#include <list>
#include <iostream>

int Main () 
{
   using namespace std;
   List <int> C1;
   List <int>::iterator c1_iter;
   
   C1.push_back (ten);
   C1.push_back (a);
   C1.push_back (a);

   cout << "C1 =";
   for (C1_iter = C1.begin (); C1_iter!= c1.end (); c1_iter++)
      cout << "" << *c1_iter;
   cout << Endl;

   C1.reverse ();
   cout << "Reversed C1 =";
   for (C1_iter = C1.begin (); C1_iter!= c1.end (); c1_iter++)
      cout << "" << *c1_iter;
   cout << Endl;
} </span>
Output results:

C1 =
Reversed C1 = 30 20 10
sort the elements by using sort ()The list member function sort has two versions, one with no parameters, the default is ascending order, and if you want to sort descending, you can use reverse in ascending order. Another version is to accept a two-yuan predicate function as a parameter, to set the criteria for sorting, such as the following one, the two-yuan predicate function Geaterthan, the specified sorting criteria is descending order

BOOL Geaterthan (const int& LSH, const int& rsh)

{

Return (Lsh > Rsh);

}

<span style= "FONT-SIZE:18PX;" >//list_sort.cpp
//compile with:/EHsc
#include <list>
#include <iostream>

int main ( )
{
   using namespace std;
   List <int> C1;
   List <int>::iterator c1_iter;
   
   C1.push_back (a);
   C1.push_back (ten);
   C1.push_back (a);

   cout << "Before sorting:c1 =";
   for (C1_iter = C1.begin (); C1_iter!= c1.end (); c1_iter++)
      cout << "" << *c1_iter;
   cout << Endl;

   C1.sort ();
   cout << "after sorting C1 =";
   for (C1_iter = C1.begin (); C1_iter!= c1.end (); c1_iter++)
      cout << "" << *c1_iter;
   cout << Endl;

   C1.sort (greater<int> ());
   cout << "After sorting with ' greater than ' operation, C1 =";
   for (C1_iter = C1.begin (); C1_iter!= c1.end (); c1_iter++)
      cout << "" << *c1_iter;
   cout << Endl;
} </span>
The output is:

Before sorting:c1 = after
sorting c1 =
The sorting with ' greater than ' operation, C1 = 30 20 10
sort the list containing the objects and delete the elements

In practical applications, STL containers are rarely used to store integers, but rather store the types that users define themselves, such as classes or structs. So how does this sort of arrangement work? For example, the list stores the phone book, where each element is an object, including the name, address, and so on, how to ensure that it can be sorted by name.

The answer is to take one of the following two ways:

<1> in the list contains the corresponding class, implement operator <

<2> provides a sort two-yuan predicate (a function that accepts two input values and returns a BOOL value indicating whether the first value is smaller than the second value)

In the actual sort call, you first decide whether to enter a two-yuan predicate, or if the sort function does not check the object element of the corresponding list to see if the operator is implemented, and if implemented, sorts the sorting criteria specified by the operator. If the two-yuan predicate function is entered, it is sorted according to its criteria;

The same is true when removing with remove, you can simply delete all elements of the object that are equal to the value of the variable in the element object. That is, the Remove function needs to provide a matching criterion to implement the = = operator in the object class, which is the deletion criterion provided for remove. such as the name in the phone book, implement an overloaded operator = = in the class as shown below

BOOL operator = = (CONST contactitem& itemtocompare) const

{

return (Itemtocompare.strcontactsname = = This->strcontactsname);

}

forward_list template class

Since C + + 11, Forward_list has been provided to support one-way lists, including header file <forward_lsit>, and the use method is similar to the list, as is the relationship between vector and deque. Forward_list can only move iterators in one Direction, and only function Push_front () is used when inserting elements, but not push_back, of course, with inserts, which can be inserted at the specified position. Summary

If you need to insert and delete elements frequently, especially in the middle, you should use std::list instead of std::vector, because in this case the vector needs to adjust the internal buffer size to support array syntax and perform expensive replication operations. And the list just needs to establish or disconnect links.

For classes that use STL containers such as list to store their objects, don't forget to implement the operator < and = = to provide the default sorting criteria and delete predicates.

When you do not need to insert and delete elements frequently, do not use the list, and use vectors and deque faster. If you do not want to delete or sort by default criteria, do not forget to provide a predicate function for sort and remove.

*************************************************************************************************************** **********************

2015-7-23



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.