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