Parsing c + + STL container list is different from Python list

Time:2022-1-7

class template

std::list

preface

🔙Return to directory (recommended Collection)Comprehensive understanding of C + + STL Standard Template Library


STL list directory

0. What is a list

definitionList is a sequence containerAllows constant time insertion and erasure operations anywhere in the sequence, as well as two-way iterations.
The list container is implemented asBidirectional linked list; Bidirectional linked lists can store each element they contain in a different and irrelevant storage location. Sorting is maintained internally through an association with each element that points to a link to the element before it and a link to the element after it.
Parsing c + + STL container list is different from Python list

1. Principle

template < class T, class Alloc = allocator<T> > class list;

🎙Parameter interpretation

  1. T: member type list:: value_ type。
  2. Alloc: the type of allocator object used to define the storage allocation model.

📜Header file

#include <list>

2. List constructor – define list

🔎notes(1) (2) (3) (4) is the C + + 98 Standard, and (5) (6) is the new C + + 11 standard

(1) Default constructor

//Construct an empty container without elements.
explicit list(const allocator_type& alloc=allocator_type());
Example: STD:: List < int > first;

(2) Fill constructor

//Construct a container containing n elements. Each element is a copy of Val (if provided).
explicit list (size_type n);
         list (size_type n, const value_type& val,
                const allocator_type& alloc =
  		 allocator_type());
Example: STD:: List < int > second (4100);

(3) Range constructor

//Construct a container that contains as many elements as the range [first, last]
//Each element places constructs in the same order from the corresponding elements in the range.
template <class InputIterator>
		list (InputIterator first, InputIterator last,
        const allocator_type& alloc = allocator_type());
Example 1: STD:: List < int > third (second. Begin()), second end());
Example 2: int myints [] = {16,2,77,29};
std::list<int> fifth (myints, myints + sizeof(myints) / 
					  sizeof(int) );

(4) Copy constructor (and copy with allocator)

//Construct a container in the same order that contains a copy of each element in X.
list (const list& x);
list (const list& x, const allocator_type& alloc);
Example: STD:: List < int > fourth (third);

(5) Move constructor (move with allocator)

//Construct a container to get the X element.
//If alloc is specified and is different from the allocator of X, the element is moved.
//Otherwise, no elements are constructed (their ownership is transferred directly).
//X is in an unspecified but valid state.
list (list&& x);
list (list&& x, const allocator_type& alloc);
Example: STD:: List < STD:: String > words8 (STD:: move (words6));

(6) Initialize list constructor

//Construct a container in the same order that contains a copy of each element in IL.
list (initializer_list<value_type> il,
     const allocator_type& alloc = allocator_type());
Example: STD:: List < STD:: String > words10 
{"the", "frogurt", "is", "also", "cursed"};

3. Output of list

🖊notesOutput cannot be achieved by counter + index []
Parsing c + + STL container list is different from Python list

(1) Output through iterator

//(1) Common forms of iterator output
void my_print(std::list<int> &li)
{
	for(std::list<int>::iterator it=li.begin();it!=li.end();it++)
	{
		std::cout<<(*it)<<" ";
	}
	std::cout<<std::endl;
}
//(2) Obtain the iterator type through auto / typedef / type alias
void my_print(std::list<int> &li)
{
	for (auto i = li.begin(); i != li.end(); i++)
	{
    	std::cout << *i << ' ';
	}
	std::cout<<std::endl;
}
//(3) Using range base, the principle is similar (2)
void my_print(std::list<int> &li)
{
	for (auto i : li)
    std::cout << i << ' ';
}

📉The above three output methods output results
Parsing c + + STL container list is different from Python list


4. Add and Delete Contents in the list

(1)list::push_ Back and list:: Pop_ back

//At the end of the list container, add a new element after its current last element.
do {
    std::cin >> myint;
    mylist.push_back (myint);
} while (myint);

//Remove the last element in the list container, effectively reducing the container size by one. 
while (!mylist.empty())
{
   sum+=mylist.back();
   mylist.pop_back();
}

(2)list::push_ Front and list:: Pop_ front

//Inserts a new element at the beginning of the list, just before its current first element
mylist.push_front (200);
mylist.push_front (300);

//Deletes an element at the beginning of the list, just before its current first element
while (!mylist.empty())
{
    std::cout << ' ' << mylist.front();
    mylist.pop_front();
}

(3) List:: insert and list:: erase

🪧insertExtends the container by inserting a new element before the element at the specified location
🪧eraseDelete a single position or a series of elements ([first, last]) from the list container.

std::list<int> mylist;
std::list<int>::iterator it;

mylist.insert (it,10);    // 1 10 2 3 4                 
mylist.insert (it,2,20);  // 1 10 20 20 2 3 4 5        ^

std::vector<int> myvector (2,30);
mylist.insert (it,myvector.begin(),myvector.end());
// 1 10 20 30 30 20 2 3 4 5
//Delete element at it1 position
mylist.erase (it1);
//Delete the element of the [it1, it2) interval
mylist.erase (it1,it2);

5. Iterator

Common member function

(1) List:: begin and list:: end

//Begin function: returns the iterator to the beginning (public member function)
//End function: return the end of iterator (public member function)
for(std::list<int>::iterator it=mylist.begin();
	it != mylist.end(); ++it)

(2) List:: rbegin and list:: rend

🪧Difference between rbegin and begin: Rbegin points to the element before the element pointed to by the member end, that is, the last element of the list.
🪧Difference between rend and end: Points to the theoretical element before the first element in the list container (considered its reverse end)
As shown below
Parsing c + + STL container list is different from Python list

//Rbegin function: return the reverse iterator to start in reverse.
//Rend function: return the reverse iterator to end in reverse.
for (std::list<int>::reverse_iterator rit=mylist.rbegin(); 
	rit!=mylist.rend(); ++rit)
    std::cout << ' ' << *rit;

(3) List:: cbegin and list:: cend

🐈🐈‍⬛differenceThe return type is iterator

//Cbegin function: return const pointing to the first element in the container_ iterator。
//Cend function: return const pointing to the last element in the container_ iterator
for (auto it = mylist.cbegin(); it != mylist.cend(); ++it)
    std::cout << ' ' << *it;

(4) List:: crbegin and list:: Credit

🔎notesCombined with the characteristics of (2) (3): reverse + iterator

//Returns a const_ reverse_ The iterator points to the last element in the container
//Returns a const_ reverse_ The iterator points to the theoretical element before the first element in the container
for(auto rit=mylist.crbegin(); rit!=mylist.crend();++rit)
    std::cout << ' ' << *rit;

6. List capacity

🔎notes: intuitive function, no explanation

(1)list::empty

//Determine whether the list is not empty and sum
 while (!mylist.empty())
  {
     sum += mylist.front();
     mylist.pop_front();
  }

(2)list::size

//Output size
for (int i=0; i<10; i++) myints.push_back(i);
  std::cout << "1. size: " << myints.size() << '\n';

(3)list::max_size

//If it is smaller than the maximum size, continue to resize and reset the size
if (i<mylist.max_size()) mylist.resize(i);

7. Element access function

(1) List:: front and list:: back

//Front: returns a reference to the first element in the list container
//Back: returns a reference to the last element in the list container.
mylist.front() -= mylist.back();
std::cout<< mylist.front()<<mylist.back();

8. Other modifiers

(1)list::clear

👻clearRemove all elements from the list container (destroyed) and keep the container with size 0.

mylist.clear();

(2)list::resize

👻resizeResize the container to contain n elements.

//n: The size of the new container, expressed in the number of elements
//Val: if n is larger than the current container size, copy its contents to the object to which the element is added.
//If not specified, the default constructor is used.
void resize (size_type n, value_type val = value_type());
//Examples
mylist.resize(5);
mylist.resize(8,100);
mylist.resize(12);

(3)list::swap

👻swapExchange content

std::list<int> first (3,100);
std::list<int> second (5,200);

first.swap(second);

(4)list:assign

👻assignAssign the new content to the list container, replace its current content, and modify its size accordingly.

first.assign (7,100);
second.assign (first.begin(),first.end());

int myints[]={1776,7,4};
first.assign (myints,myints+3);

9. List operation

(1) Splice list:: splice

mylist1.splice (it, mylist2);     
mylist2.splice (mylist2.begin(),mylist1, it);// "it" is now invalid.

it = mylist1.begin();
std::advance(it,3); // "it" points now to 30

mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
  

(2) Delete duplicate values list:: unique

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

mylist.unique();
mylist.unique (same_integral_part);
mylist.unique (is_near());

(3) Sort list:: sort

mylist.sort();
mylist.sort(compare_nocase);

// comparison, not case sensitive.
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() );
}


10. List comparison between Python and C + +

From the perspective of data structure

  • STL: List bidirectional linked list
  • Python: list is similar to array

Thank you very much for reading. If you help, give me a praise. Thank you!

Recommended Today

Proper memory alignment in go language

problem type Part1 struct { a bool b int32 c int8 d int64 e byte } Before we start, I want you to calculatePart1What is the total occupancy size? func main() { fmt.Printf(“bool size: %d\n”, unsafe.Sizeof(bool(true))) fmt.Printf(“int32 size: %d\n”, unsafe.Sizeof(int32(0))) fmt.Printf(“int8 size: %d\n”, unsafe.Sizeof(int8(0))) fmt.Printf(“int64 size: %d\n”, unsafe.Sizeof(int64(0))) fmt.Printf(“byte size: %d\n”, unsafe.Sizeof(byte(0))) fmt.Printf(“string size: %d\n”, […]