C++ STL 中的列表運算子 =
任務是展示C++ STL中列表運算子 = 的功能。
STL中的列表是什麼?
列表是容器,允許在序列中的任何位置進行常數時間插入和刪除操作。列表實現為雙向連結串列。列表允許非連續記憶體分配。與陣列、向量和雙端佇列相比,列表在容器的任何位置執行元素的插入、提取和移動操作的效能更好。在列表中,直接訪問元素的速度較慢,列表類似於forward_list,但forward_list物件是單向連結串列,它們只能向前迭代。
運算子 = 的用途是什麼?
此運算子用於透過替換列表中的現有元素來為列表分配新元素。它會根據內容修改新列表的大小。我們從中獲取新元素的另一個容器與第一個容器具有相同的資料型別。
語法:listname1 = listname2
示例
Input List1: 50 60 80 90 List2: 90 80 70 60 Output List1: 90 80 70 60 Input List1: E N E R G Y List2: C A P T I O N Output List1: C A P T I O N
可以遵循的方法
首先,我們初始化兩個列表。
然後我們使用 = 運算子。
然後我們列印新的列表。
使用上述方法,我們可以為列表分配新元素。此運算子的工作方式與swap()函式類似,此運算子將list2的內容與list1交換,但它不會將list1的內容與list2交換,而是將新內容賦值給list1。
示例
// C++ code to demonstrate the working of list = operator in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
// initializing two lists
list<int> list1 = { 10, 20, 30, 40, 50 };
cout<< “ List1: “;
for( auto x = list1.begin( ); x != list1.end( ); ++x)
cout<< *x << “ “;
list<int> list2 = { 40, 50, 60, 70, 80 };
cout<< “ List2: “;
for( auto x = list2.begin( ); x != list2.end( ); ++x)
cout<< *x << “ “;
list1 = list2;
// printing new content of list
cout<< “ New contents of List1 is :”;
for(auto x = list1.begin( ); x != list1.end( ); ++x)
cout<< *x<< “ “;
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出
Input - List1: 10 20 30 40 50 List2: 40 50 60 70 80 Output - New content of List1 is: 40 50 60 70 80
示例
// C++ code to demonstrate the working of list = operator in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
// initializing two lists
list<char> list1 = { 'C', 'H', 'A', 'R', 'G', 'E', 'R' };
cout<< " List1: ";
for( auto x = list1.begin( ); x != list1.end( ); ++x)
cout<< *x << " ";
List<char> list2 = { 'P', 'O', 'I', 'N', 'T' };
cout<< " List2: ";
for( auto x = list2.begin( ); x != list2.end( ); ++x)
cout<< *x << " ";
list1 = list2;
// printing new content of list
cout<< " New contents of List1 is :";
for(auto x = list1.begin( ); x != list1.end( ); ++x)
cout<< *x<< " ";
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出
Input - List1: C H A R G E R List2: P O I N T Output - New contents of List1 is: P O I N T
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP