首页 文章资讯内容详情

列出C ++ STL中的assign()函数

2026-06-04 1 花语

给出的任务是显示C++中assign()函数的工作。

list::assign()函数是C++标准模板库的一部分。它用于将值分配给列表,也可以将值从一个列表复制到另一个列表。

应该包含<list>头文件才能调用此函数。

语法

分配新值的语法如下-

List_Name.assign(size,value)

语法

将值从一个列表复制到另一个列表的语法如下-

First_List.assign(Second_List.begin(),Second_list.end())

参量

该函数有两个参数-

第一个是size,它表示列表的大小,第二个是value,它表示要存储在列表内部的数据值。

返回值

该函数没有返回值。

示例

Input: Lt.assign(3,10) Output: The size of list Lt is 3. The elements of the list Lt are 10 10 10.

说明-

以下示例说明了如何使用assign()函数分配列表的大小和值。我们将在列表函数中传递的第一个值成为列表的大小,在这种情况下为3,第二个元素是分配给列表每个位置的值,此处为10。

示例

Input: int array[5] = { 1, 2, 3, 4 } Lt.assign(array,array+3) Output: The size of list Lt is 3. The elements of the list Lt are 1 2 3.

说明-

以下示例说明了如何使用数组将值分配给列表。我们将分配给列表的元素总数成为列表的大小。

用户只需要简单地将数组的名称作为参数传递给assign()函数,第二个参数应为数组的名称,然后是“+”号,后跟用户想要的元素数分配给列表。

在上面的例子中,我们写了3,因此数组的前三个元素将分配给列表。

如果我们写的数字大于数组中存在的元素的数量,比如说6,那么程序将不会显示任何错误,而是列表的大小将变为6,并且将分配列表中的额外位置值为零。

以下程序中使用的方法如下-

首先创建一个函数ShowList(list<int>L),它将显示列表中的元素。

创建一个迭代器,假设它包含要显示的列表的初始元素。

使循环运行,直到itr到达列表的最后一个元素。

然后在main()函数内部,使用list<int>创建三个列表,假设L1,L2和L3使其接受int类型的值,然后创建int类型的数组,例如arr[]并为其分配一些值。

然后使用assign()函数将大小和一些值分配给列表L1,然后将列表L1传递给ShowDisplay()函数。

然后,使用assign()函数将列表L1的元素复制到L2中,并将列表L2传递到ShowList()函数中。

然后,使用assign()函数将数组arr[]的元素复制到列表L3中,并将列表L3传递到DisplayList()函数中。

算法

Start Step 1-> Declare function DisplayList(list<int> L) for showing list elements Declare iterator itr Loop For itr=L.begin() and itr!=L.end() and itr++ Print *itr End Step 2-> In function main() Declare lists L1,L2,L3 Initialize array arr[] Call L1.assign(size,value) Print L1.size(); Call function DisplayList(L1) to display L1 Call L2.assign(L1.begin(),L1.end()) Print L2.size(); Call function DisplayList(L2) to display L2 Call L3.assign(arr,arr+4) Print L3.size(); Call function DisplayList(L3) to display L3 Stop

示例

#include<iostream> #include<list> using namespace std; int ShowList(list<int> L) { cout<<"The elements of the list are "; list<int>::iterator itr; for(itr=L.begin(); itr!=L.end(); itr++) { cout<<*itr<<" "; } cout<<"\n"; } int main() { list<int> L1; list<int> L2; list<int> L3; int arr[10] = { 6, 7, 2, 4 }; //assigning size and values to list L1 L1.assign(3,20); cout<<"The size of list L1 is "<<L1.size()<<"\n"; ShowList(L1); //copying the elements of L1 into L3 L2.assign(L1.begin(),L1.end()); cout<<"The size of list is L2 "<<L2.size()<<"\n"; ShowList(L2); //copying the elements of arr[] into list L3 L3.assign(arr,arr+4); cout<<"The size of list is L3 "<<L3.size()<<"\n"; ShowList(L3); return 0; }

输出结果

如果我们运行上面的代码,它将生成以下输出-

The size of list L1 is 3 The elements of the list are 20 20 20 The size of list L2 is 3 The elements of the list are 20 20 20 The size of list L3 is 4 The elements of the list are 6 7 2 4

说明

对于列表L1,我们在产生上述输出的assign()函数中将size设置为3,将value设置为20。

然后,我们将列表L1的元素复制到该L2中,该L2使L2具有与L1相同的大小和值,如在输出中看到的那样。

然后,我们使用assign函数复制数组arr[]的所有元素,这使L3的大小等于4,并且其元素与输出中的数组元素相同。