C++中的assign函数

assign函数是C++标准库中许多容器类(如vector、list、string等)提供的成员函数,用于替换容器中的内容。它提供了一种灵活的方式来修改容器内容,比直接赋值更灵活。

基本用法

1. vector的assign函数

vector的assign函数主要有三种形式:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec;
    
    // 形式1: 用n个相同元素赋值
    vec.assign(5, 10); // 5个值为10的元素
    cout << "assign(5, 10): ";
    for (int num : vec) cout << num << " ";
    cout << endl;
    
    // 形式2: 用迭代器范围赋值
    vector<int> other = {1, 2, 3, 4, 5};
    vec.assign(other.begin() + 1, other.end() - 1);
    cout << "assign(begin+1, end-1): ";
    for (int num : vec) cout << num << " ";
    cout << endl;
    
    // 形式3: 用初始化列表赋值 (C++11)
    vec.assign({6, 7, 8, 9});
    cout << "assign({6,7,8,9}): ";
    for (int num : vec) cout << num << " ";
    cout << endl;
    
    return 0;
}

输出:

assign(5, 10): 10 10 10 10 10 
assign(begin+1, end-1): 2 3 4 
assign({6,7,8,9}): 6 7 8 9 

形式1与形式2的区别:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
迭代器的基本操作
不同类型的迭代器支持不同的操作,但大多数迭代器都支持以下基本操作:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};
    
    // 获取迭代器
    vector<int>::iterator it = vec.begin();
    
    // 解引用迭代器访问元素
    cout << "First element: " << *it << endl;
    
    // 移动迭代器
    ++it; // 向前移动
    cout << "Second element: " << *it << endl;
    
    // 比较迭代器
    if (it != vec.end()) {
        cout << "Iterator is not at the end" << endl;
    }
    
    return 0;
}
2. string的assign函数

string类也提供了多种assign重载:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    
    // 形式1: 用n个相同字符赋值
    str.assign(5, 'A');
    cout << "assign(5, 'A'): " << str << endl;
    
    // 形式2: 用另一个字符串赋值
    string other = "Hello World";
    str.assign(other);
    cout << "assign(other): " << str << endl;
    
    // 形式3: 用另一个字符串的子串赋值
    str.assign(other, 6, 5); // 从位置6开始,长度为5
    cout << "assign(other, 6, 5): " << str << endl;
    
    // 形式4: 用C风格字符串赋值
    str.assign("C-style string");
    cout << "assign(\"C-style string\"): " << str << endl;
    
    // 形式5: 用C风格字符串的前n个字符赋值
    str.assign("Hello World", 5);
    cout << "assign(\"Hello World\", 5): " << str << endl;
    
    return 0;
}

输出:

assign(5, 'A'): AAAAA
assign(other): Hello World
assign(other, 6, 5): World
assign("C-style string"): C-style string
assign("Hello World", 5): Hello
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值