天天看點

C++ STL forward_list使用C++ forward_list使用

C++ forward_list使用

forward_list

  • C++ forward_list使用
    •  概述
    •  建立forward_list
      •   構造函數
      •   opertor=
      •   assign
    •  元素通路
      •   front
    •  疊代器
      •   begin\cbegin
      •   end\cend
      •   before_begin, cbefore_begin
    •  容量
      •   empty
      •   max_size
    •  修改器
      •   clear
      •   insert_after
      •   emplace_after
      •   erase_after
      •   push_front
      •   emplace_front
      •   pop_front
      •   resize
      •   swap
    •  操作
      •   merge
      •   splice_after
      •   remove,remove_if
      •   reverse
      •   unique
      •   sort
    •  非成員函數
      •   operator==
      •   std::swap
      •   erase(std::forward_list)
      •   erase_if(std::forward_list)

 概述

定義于頭檔案<forward_list>,std::forward_list 是支援從容器中的任何位置快速插入和移除元素的容器。不支援快速随機通路。它實作為單連結清單,且實質上與其在 C 中實作相比無任何開銷。與 std::list 相比,此容器在不需要雙向疊代時提供更有效地利用空間的存儲。

在連結清單内或跨數個連結清單添加、移除和移動元素,不會非法化目前指代連結清單中其他元素的疊代器。然而,在從連結清單移除元素(通過 erase_after )時,指代對應元素的疊代器或引用會被非法化。

類模闆:

template<
		class T,
		class Allocator = std::allocator<T>
	> class forward_list;
           

模闆形參:

  T - 元素的類型;

  Allocator - 用于擷取/釋放記憶體及構造/析構記憶體中元素的配置設定器。

 建立forward_list

  構造函數

  從各種資料源構造新容器,可選地使用使用者提供的配置設定器 alloc 。

  與 vector、deque、list 構造函數一樣。

定義:

// 1、預設構造函數
forward_list();	

// 2、構造擁有給定配置設定器 alloc 的空容器。								
explicit forward_list( const Allocator& alloc );	

// 3、構造擁有 count 個有值 value 的元素的容器。
forward_list( size_type count,					
                 const T& value,
                 const Allocator& alloc = Allocator());
                 
// 4、構造擁有個 count 預設插入的 T 執行個體的容器。不進行複制。
explicit forward_list( size_type count, const Allocator& alloc = Allocator() );	

// 5、構造擁有範圍 [first, last) 内容的容器。
template< class InputIt >
forward_list( InputIt first, InputIt last,		
        const Allocator& alloc = Allocator() );

// 6、複制構造函數
forward_list( const forward_list& other );		

// 7、構造擁有 other 内容的容器,以 alloc 為配置設定器。		
forward_list( const forward_list& other, const Allocator& alloc ); 		

// 8、移動構造函數
forward_list( forward_list&& other );				 	

// 9、有配置設定器擴充的移動構造函數。
forward_list( forward_list&& other, const Allocator& alloc );		

// 10、構造擁有 initializer_list init 内容的容器。
forward_list( std::initializer_list<T> init,		
        const Allocator& alloc = Allocator() );
           

用法:

// 1、預設構造函數
    std::forward_list<std::string> words1;
    
    // 3、構造擁有 count 個有值 value 的元素的容器
    std::forward_list<std::string> words3(5, "Mo");	//words2 為 {"Mo", "Mo", "Mo", "Mo", "Mo"}
    
    // 5、構造擁有範圍 [first, last) 内容的容器
    std::forward_list<std::string> words5(words3.begin(), words3.end());
    
    // 6、複制構造函數
    std::forward_list<std::string> words6(words5);
    
    // 8、移動構造函數
    std::forward_list<std::string> words8(std::move(words6));
    
    // 10、C++ 11 初始化器清單文法:
    std::forward_list<std::string> words10 {"the", "frogurt", "is", "also", "cursed"};
           

  opertor=

  替換容器的内容。

定義:

forward_list& operator=( const forward_list& other );	// 複制指派運算符。
forward_list& operator=( forward_list&& other );		// 移動指派運算符。
forward_list& operator=( std::initializer_list<T> ilist ); // 以 initializer_list ilist 所辨別者替換内容。
           

用法:

std::forward_list<int> nums1 {3, 1, 4, 6, 5, 9};
    std::forward_list<int> nums2;
    std::forward_list<int> nums3;

    // 從 nums1 複制指派資料到 nums2
    nums2 = nums1;
    // 從 nums1 移動指派資料到 nums3,
    nums3 = std::move(nums1);
    // initializer_list 的複制指派複制資料給 nums3
    nums3 = {1, 2, 3};
           

  assign

  替換容器的内容。

定義:

void assign( size_type count, const T& value ); // 1、以 count 份 value 的副本替換内容。
template< class InputIt > 						// 2、以範圍 [first, last) 中元素的副本替換内容。
		void assign( InputIt first, InputIt last );
void assign( std::initializer_list<T> ilist );	// 3、以來自 initializer_list ilist 的元素替換内容。
           

用法:

// 以 count 份 value 的副本替換内容
    std::forward_list<char> characters;
    characters.assign(5, 'a');

	// 以範圍 [first, last) 中元素的副本替換内容
	std::forward_list<char> vchar;
	vchar.assign(characters.begin(), characters.end());

	// 以來自 initializer_list ilist 的元素替換内容
    characters.assign({'\n', 'C', '+', '+', '1', '1', '\n'});
           

 元素通路

  front

  傳回到容器首元素的引用。

對于容器 c ,表達式 c.front() 等價于 *c.begin() 。

定義:

reference front();
const_reference front() const;
           

用法:

std::forward_list<char> letters {'o', 'm', 'g', 'w', 't', 'f'};
 	if (!letters.empty()) {
 		std::cout << letters.front() << std::out;	// 輸出 o
 	}
           

 疊代器

  begin\cbegin

C++ STL forward_list使用C++ forward_list使用

  傳回指向 forward_list 首元素的疊代器。 cbegin中的c表示const,即傳回const_iterator,不允許通過疊代器修改元素。

若 forward_list 為空,則傳回的疊代器将等于 end() 。

定義:

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

用法:

std::forward_list<int> vi = {1, 2, 3, 4, 5, 6};
 	std::cout << *(vi.begin()) << std::endl;	// 輸出 1	
 	*(vi.begin()) = 0;
 	std::cout << *(vi.cbegin()) << std::endl;	// 輸出 0
           

  end\cend

指向後随最後元素的疊代器。

定義:

iterator end();
const_iterator cend() const noexcept;
           

用法:

std::forward_list<char> vc;
	if (vc.begin() == vc.end())
	{
		std::cout << "forward_list is empty." << std::endl;
	}
           

  before_begin, cbefore_begin

  傳回指向首元素前一進制素的疊代器。

定義:

iterator before_begin() noexcept;			// (C++11 起)
const_iterator before_begin() const noexcept;	// (C++11 起)
const_iterator cbefore_begin() const noexcept;	// (C++11 起)
           

 容量

  empty

  檢查容器是否無元素,即是否 begin() == end() 。

定義:

用法:

forward_list<int> v;
	bool flag = v.empty();	// 輸出 true
           

  max_size

  傳回根據系統或庫實作限制的容器可保有的元素最大數量,即對于最大容器的 std::distance(begin(), end()) 。

定義:

用法:

std::forward_list<int> vi;
	std::cout << vi.max_size() << std::endl;	// 可能輸出 4611686018427387903
	std::forward_list<char> vc;
	std::cout << vc.max_size() << std::endl;	// 可能輸出 18446744073709551615
           

 修改器

  clear

  從容器擦除所有元素。此調用後 size() 傳回零。

  非法化任何指代所含元素的引用、指針或疊代器。任何尾後疊代器亦被非法化。

定義:

用法:

std::forward_list<int> container{1, 2, 3};
	container.clear();
	std::cout << container.size() << std::endl;		// 輸出 0
           

  insert_after

  在容器中的指定位置後插入元素。

定義:

// 1、在 pos 後插入 value
iterator insert_after( const_iterator pos, const T& value );

// 2、在 pos 後插入 value
iterator insert_after( const_iterator pos, T&& value );	

// 3、在 pos 後插入 value 的 count 個副本
void insert_after( const_iterator pos, size_type count, const T& value );	

// 4、在 pos 後插入來自範圍 [first, last) 的元素
template< class InputIt >	
	void insert_after( const_iterator pos, InputIt first, InputIt last);

// 5、在 pos 前插入來自 initializer_list ilist 的元素
iterator insert_after( const_iterator pos, std::initializer_list<T> ilist );	
           

用法:

std::forward_list<int> vec(3,100);
 
 	// 1,2、在 pos 前插入 value
    auto it = vec.begin();	
    it = vec.insert_after(it, 200);	// 100 200 100 100
 
 	// 3、插入多個value
    vec.insert_after(it,2,300);		// 100 200 300 300 100 100
 
 	// 4、在 pos 前插入來自範圍 [first, last) 的元素
    std::forward_list<int> vec2(2,400);
    vec.insert_after(vec.begin(), vec2.begin(), vec2.end());	// 100 400 400 200 300 300 100 100
    
 	// 5、在 pos 前插入來自 initializer_list ilist 的元素
    int arr[] = { 501,502,503 };
    vec.insert_after(vec.begin(), arr, arr+3);	// 100 501 502 503 400 400 200 300 300 100 100
           

  emplace_after

  在容器中的指定位置後插入新元素。

定義:

template< class... Args >
iterator emplace_after( const_iterator pos, Args&&... args );
           

用法:

std::forward_list<int> v {1, 2, 3};
	v.emplace(v.begin(), 4);	// v : 1, 4, 2, 3
           

  erase_after

  從容器擦除指定的元素。

定義:

// 1、移除位于 pos 的元素。
iterator erase_after( const_iterator pos );

// 2、移除範圍 [first; last) 中的元素。
iterator erase_after( const_iterator first, iterator last );
           

用法:

std::forward_list<int> c {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
	c.erase_after(c.begin());			// 1 2 3 4 5 6 7 8 9

	c.erase_after(c.begin(), c.end());	
           

  push_front

  前附給定元素 value 到容器起始。 所有疊代器,包含尾後疊代器,都被非法化

定義:

void push_front( const T& value );
void push_front( T&& value );
           

用法:

std::forward_list<int> numbers {1, 2};
	
    numbers.push_front(0);		// {0, 1, 2}
           

  emplace_front

  插入新元素到容器起始。

定義:

// C++ 11
template< class... Args >
	void emplace_front( Args&&... args );

// C++ 17
template< class... Args >
	reference emplace_front( Args&&... args );
           

  pop_front

  移除容器首元素。 指向被擦除元素的疊代器和引用被非法化。

定義:

用法:

std::forward_list<int> c = {1, 2, 3};  
    c.pop_front();	// c : 2, 3
           

  resize

  重設容器大小以容納 count 個元素。 若目前大小大于 count ,則減小容器為其首 count 個元素。若目前大小小于 count ,1) 則後附額外的預設插入的元素,2) 則後附額外的 value 的副本。

定義:

void resize( size_type count );
void resize( size_type count, const value_type& value );
           

用法:

std::forward_list<int> c = {1, 2, 3};  
    c.resize(5);	// c : 1, 2, 3, 0, 0
    c.resize(2);	// c : 1, 2
           

  swap

   将内容與 other 的交換。 不在單獨的元素上調用任何移動、複制或交換操作。

定義:

用法:

std::forward_list<int> a1{1, 2, 3}, a2{4, 5};
	a1.swap(a2);
           

 操作

  merge

  歸并二個已排序連結清單為一個。 連結清單應以升序排序。

定義:

void merge( forward_list& other );
void merge( forward_list&& other );

template <class Compare>
	void merge( forward_list& other, Compare comp );
template <class Compare>
	void merge( forward_list&& other, Compare comp );
           

用法:

std::forward_list<int> list1 = { 5,9,0,1,3 };
    std::forward_list<int> list2 = { 8,7,2,6,4 };
 
    list1.sort();
    list2.sort();

    list1.merge(list2);		// list1 : 0 1 2 3 4 5 6 7 8 9
    list2.empty();			// list2為空
           

  splice_after

  從一個 forward_list 轉移元素給另一個。 不複制或移動元素,僅重指向連結清單結點的内部指針。

定義:

void splice_after( const_iterator pos, forward_list& other );
// 1、從 other 轉移所有元素到 *this 中。元素被插入到 pos 所指向的元素之前。操作後容器 other 變為空。若 other 與 *this 指代同一對象則行為未定義。
void splice_after( const_iterator pos, forward_list&& other );

void splice_after( const_iterator pos, forward_list& other, const_iterator it );
// 2、從 other 轉移 it 所指向的元素到 *this 。元素被插入到 pos 所指向的元素之前。
void splice_after( const_iterator pos, forward_list&& other, const_iterator it );

void splice_after( const_iterator pos, forward_list& other, const_iterator first, const_iterator last );
// 3、從 other 轉移範圍 [first, last) 中的元素到 *this 。元素被插入到 pos 所指向的元素之前。若 pos 是範圍 (first,last) 中的疊代器則行為未定義。
void splice_after( const_iterator pos, forward_list&& other, const_iterator first, const_iterator last );
           

用法:

std::forward_list<int> l1 = {1, 2, 3, 4, 5};
    std::forward_list<int> l2 = {10, 11, 12};
 
    l2.splice_after(l2.cbegin(), l1, l1.cbegin(), l1.cend());
    // 不等價于 l2.splice_after(l2.cbegin(), l1);

	// l1 : 1
	// l2 : 10 2 3 4 5 11 12
           

  remove,remove_if

  移除所有滿足特定标準的元素。 第一版本移除所有等于 value 的元素,第二版本移除所有謂詞 p 對它傳回 true 的元素。

定義:

void remove( const T& value );				// (C++20 前)
size_type remove( const T& value );			// (C++20 起)

template< class UnaryPredicate >			// (C++20 前)
	void remove_if( UnaryPredicate p );
template< class UnaryPredicate >			// (C++20 起)
	size_type remove_if( UnaryPredicate p );
           

用法:

std::forward_list<int> l = { 1,100,2,3,10,1,11,-1,12 };
 
 	// 移除兩個等于 1 的元素
    l.remove(1); 				// 100, 2, 3, 10, 11, -1, 12

	// 移除全部大于 10 的元素
    l.remove_if([](int n){ return n > 10; }); 	//  2, 3, 10, -1
           

  reverse

  逆轉容器中的元素順序。 不非法化任何引用或疊代器。

定義:

用法:

std::forward_list<int> list = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	list.reverse();			// 9 8 7 6 5 4 3 2 1 0
           

  unique

  **從容器移除所有連續的重複元素。隻留下相等元素組中的第一個元素。 **第一版本用 operator== 比較元素,第二版本用二進制謂詞 p 比較元素

定義:

void unique();			// (C++20 前)
size_type unique();		// (C++20 後)

template< class BinaryPredicate >
	void unique( BinaryPredicate p );		// (C++20 前)
template< class BinaryPredicate >
	size_type unique( BinaryPredicate p );  // (C++20 起)
           

用法:

std::forward_list<int> x = {1, 2, 2, 3, 3, 2, 1, 1, 2};
 
 	x.unique();
  	for (auto val : x)
  	{
    	std::cout << ' ' << val;		// 1 2 3 2 1 2
    }
           

  sort

  以升序排序元素。保持相等元素的順序。 第一版本用 operator< 比較元素,第二版本用給定的比較函數 comp 。

定義:

void sort();

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

用法:

std::forward_list<int> list = { 8,7,5,9,0,1,3,2,6,4 };
 
    list.sort();
    std::cout << "ascending:  " << list << "\n";	// 0 1 2 3 4 5 6 7 8 9
    list.sort(std::greater<int>());
    std::cout << "descending: " << list << "\n";	// 9 8 7 6 5 4 3 2 1 0
           

 非成員函數

  operator==

  檢查 lhs 與 rhs 的内容是否相等,即它們是否擁有相同數量的元素且 lhs 中每個元素與 rhs 的同位置元素比較相等。

定義:

template< class T, class Alloc >
bool operator==( const std::forward_list<T,Alloc>& lhs,
                 const std::forward_list<T,Alloc>& rhs );
           

用法:

std::forward_list<int> alice{1, 2, 3};
	std::forward_list<int> bob{7, 8, 9, 10};
	std::forward_list<int> eve{1, 2, 3};
 
	// 比較不相等的容器
	std::cout << "alice == bob returns " << (alice == bob) << std::endl;	//輸出 false
	// 比較相等的容器
	std::cout << "alice == eve returns " << (alice == eve) << std::endl;	//輸出 true
           

  std::swap

  為 std::forward_list 特化 std::swap 算法。交換 lhs 與 rhs 的内容。調用 lhs.swap(rhs) 。

定義:

template< class T, class Alloc >
void swap( std::forward_list<T,Alloc>& lhs,
           std::forward_list<T,Alloc>& rhs );
           

用法:

std::forward_list<int> alice{1, 2, 3};
	std::forward_list<int> bob{7, 8, 9, 10};
	//交換容器
	std::swap(alice,bob);
	//交換後:alice : 7 8 9 10	bob : 1 2 3
           

  erase(std::forward_list)

  從容器中擦除所有比較等于 value 的元素。(C++ 20)

定義:

template< class T, class Alloc, class U >
constexpr typename std::forward_list<T,Alloc>::size_type
    erase(std::forward_list<T,Alloc>& c, const U& value);
           

用法:

std::forward_list<char> cnt {'1', '2', '3', '5', '6'};
	auto erased = std::erase(cnt, '3');
           

  erase_if(std::forward_list)

  從容器中擦除所有滿足 pred 的元素。(C++ 20)

定義:

template< class T, class Alloc, class U >
constexpr typename std::forward_list<T,Alloc>::size_type
     erase_if(std::forward_list<T,Alloc>& c, Pred pred);
           

用法:

std::forward_list<char> cnt {'1', '2', '3', '5', '6'};
	std::erase_if(cnt, 
		[](char x) { return (x - '0') % 2 == 0; }
		);
           

繼續閱讀