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