C++中list的赋值和交换

本文通过示例详细介绍了C++中list容器的赋值(包括operator=和assign方法)以及交换(swap函数)操作。示例展示了如何初始化、赋值和交换list,帮助理解这些基本操作在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

list的赋值和交换

在这里插入图片描述

#include<iostream>
#include<list>
#include <string>

using namespace std;

/**
 * 打印list
 * @param l要打印的list
 */
void printList(const list<int> &l) {
    for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;
}

/**
 * 赋值测试
 */
void test() {

    list<int> l1;

    l1.push_back(10);
    l1.push_back(20);
    l1.push_back(30);
    l1.push_back(40);

    printList(l1);//10 20 30 40

    list<int> l2;
    //operator=赋值
    l2 = l1;
    printList(l2);//10 20 30 40

    list<int> l3;
    //区间赋值
    l3.assign(l1.begin(), l1.end());
    printList(l3);//10 20 30 40

    //n个elem赋值
    list<int> l4;
    l4.assign(10, 9);
    printList(l4);//9 9 9 9 9 9 9 9 9 9

}

/**
 * 交换测试
 */
void test2() {

    list<int> l1;

    l1.push_back(10);
    l1.push_back(20);
    l1.push_back(30);
    l1.push_back(40);

    list<int> l2;
    l2.assign(10, 9);
    cout << "交换前:" << endl;
    printList(l1);
    printList(l2);

    //交换
    l1.swap(l2);
    cout << "交换后:" << endl;
    printList(l1);
    printList(l2);

}

int main() {
//    test();
//    test2();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值