STL——容器(List)list 的赋值操作

STL——容器(List)list 的赋值操作

list.assign(beg, end);

//将[beg, end)区间中的数据拷贝赋值给本身

1 #include

2 #include

3

4 using namespace std;

5

6 int main()

7 {

8 int num[] = { 111,222,333,444,555 };

9 list listInt_A(num, num + size(num));

10 list listInt_B;

11

12 cout << "遍历 listInt_A:";

13 for (list::iterator it = listInt_A.begin(); it != listInt_A.end(); it++)

14 {

15 cout << *it << " ";

16 }

17 cout << endl;

18

19 listInt_B.assign(++listInt_A.begin(), --listInt_A.end());

20 cout << "遍历 listInt_B:";

21 for (list::iterator it = listInt_B.begin(); it != listInt_B.end(); it++)

22 {

23 cout << *it << " ";

24 }

25 cout << endl;

26

27 return 0;

28 }

打印结果:

end()是结束符,但没有打印出来555,是因为前开后闭,

list.assign(n, elem);

//将n个elem拷贝赋值给本身

1 #include

2 #include

3

4 using namespace std;

5

6 int main()

7 {

8 list listInt_A(5, 888);

9

10 cout << "遍历 listInt_A:";

11 for (list::iterator it = listInt_A.begin(); it != listInt_A.end(); it++)

12 {

13 cout << *it << " ";

14 }

15 cout << endl;

16

17 return 0;

18 }

打印结果:

list& operator=(const list& lst);

//重载等号操作符

1 #include

2 #include

3

4 using namespace std;

5

6 int main()

7 {

8 int num[] = { 111,222,333,444,555 };

9 list listInt_A(num, num + size(num));

10 list listInt_B;

11

12 cout << "遍历 listInt_A:";

13 for (list::iterator it = listInt_A.begin(); it != listInt_A.end(); it++)

14 {

15 cout << *it << " ";

16 }

17 cout << endl;

18

19 listInt_B = listInt_A;

20 cout << "遍历 listInt_B:";

21 for (list::iterator it = listInt_B.begin(); it != listInt_B.end(); it++)

22 {

23 cout << *it << " ";

24 }

25 cout << endl;

26

27 return 0;

28 }

打印结果:

list.swap(lst);

//将lst与本身的元素互换

1 #include

2 #include

3

4 using namespace std;

5

6 int main()

7 {

8 int num[] = { 111,222,333,444,555 };

9 list listInt_A(num, num + size(num));

10 list listInt_B(5, 888);

11

12 cout << "互换前 遍历 listInt_A:";

13 for (list::iterator it = listInt_A.begin(); it != listInt_A.end(); it++)

14 {

15 cout << *it << " ";

16 }

17 cout << endl;

18 cout << "互换前 遍历 listInt_B:";

19 for (list::iterator it = listInt_B.begin(); it != listInt_B.end(); it++)

20 {

21 cout << *it << " ";

22 }

23 cout << endl;

24

25 //互换

26 listInt_A.swap(listInt_B);

27 cout << "互换后 遍历 listInt_A:";

28 for (list::iterator it = listInt_A.begin(); it != listInt_A.end(); it++)

29 {

30 cout << *it << " ";

31 }

32 cout << endl;

33 cout << "互换后 遍历 listInt_B:";

34 for (list::iterator it = listInt_B.begin(); it != listInt_B.end(); it++)

35 {

36 cout << *it << " ";

37 }

38 cout << endl;

39

40 return 0;

41 }

打印结果:

===================================================================================================================

🖌️ 相关文章

月亮石加多少防御
365bet代理

月亮石加多少防御

📅 11-26 👁️ 8509
超神學院
365bet体育在线15

超神學院

📅 06-27 👁️ 7366
如何查看电脑端口号?详细指南与安全策略
365bet体育在线15

如何查看电脑端口号?详细指南与安全策略

📅 08-01 👁️ 6794