C++ STL 中的 forward_list::operator =


在本文中,我们将讨论 C++ 中 forward_list::operator = 的工作原理、语法和示例。

什么是 STL 中的 Forward_list?

Forward list 是一种序列容器,允许在序列中的任何位置进行常数时间插入和删除操作。Forward list 以单链表的形式实现。顺序通过将每个元素与序列中下一个元素的链接关联来维护。

什么是 forward_list::operator =?

Forward_list::operator = 用于通过替换已存在的元素来为 forward_list 容器分配新值。此运算符还会根据新值修改 forward_list 容器的大小。

语法

Forward_container1 = (forward_container2);

此函数接受另一个相同类型的 forward_list 容器。

返回值

它返回“*this”指针。

在下面的代码中,我们创建了两个 forward list 并向其中插入元素,然后我们将使用“=”运算符用 forward list 2 中的元素覆盖 forward list 1 中的元素。

示例

 在线演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList1 = {10, 20, 30 };
   forward_list<int> forwardList2 = { 0, 1, 2, 3 };
   forwardList1 = forwardList2;
   cout << "my forwardList1 after using = operator with forwardList2\n";
   for (auto i = forwardList1.begin(); i != forwardList1.end(); ++i)
      cout << ' ' << *i;
   return 0;
}

输出

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

my forwardList1 after using = operator with forwardList2
0 1 2 3

示例

在下面的代码中,我们创建了两个 forward list 并向其中插入元素,然后我们将使用“=”运算符用 forward list 2 中的元素覆盖 forward list 1 中的元素。现在的主要任务是检查 forward list 2 的状态,即它是否也会发生变化。

 在线演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList1 = {10, 20, 30 };
   forward_list<int> forwardList2 = { 0, 1, 2, 3 };
   forwardList1 = forwardList2;
   cout << "my forwardList1 after using = operator with forwardList2\n";
   for (auto i = forwardList1.begin(); i != forwardList1.end(); ++i)
      cout << ' ' << *i;
   cout << "\n my forwardList2 after using = operator with forwardList1\n";
   for (auto i = forwardList2.begin(); i != forwardList2.end(); ++i)
      cout << ' ' << *i;
   return 0;
}

输出

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

my forwardList1 after using = operator with forwardList2
0 1 2 3
my forwardList2 after using = operator with forwardList1
0 1 2 3

更新于: 2020年3月2日

179 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.