参考c++官方手册
vector::assign
是C++标准模板库中的一个函数,它的主要功能是给vector容器重新赋值。具体来说,vector::assign
函数会删除vector中的所有元素,并根据用户提供的参数重新填充。
这个函数有三种形式:
-
template <class InputIterator> void assign (InputIterator first, InputIterator last);
此形式将vector的内容替换为[first,last)区间内的元素。
注意:此处的方括号表示闭区间,圆括号表示开区间,也就是包含first,不包含last。 -
void assign (size_type n, const value_type& val);
此形式将vector的内容替换为n个复制的val。 -
void assign (initializer_list<value_type> il);
此形式将vector的内容替换为初始化列表il中的元素。
下面是一些使用vector::assign
的例子:
第一种
#include <iostream>
#include <vector>int main()
{// 创建一个vector对象v1和v2std::vector<int> v1;std::vector<int> v2;// 使用push_back()函数给v1添加元素for (int i = 1; i <= 5; i++)v1.push_back(i);// 使用迭代器范围赋值v2.assign(v1.begin(), v1.end());std::cout << "The vector elements of v2 are: ";for (int i = 0; i < v2.size(); i++)std::cout << v2[i] << " ";return 0;
}
第二和第三
#include <iostream>
#include <vector>
int main()
{// 创建一个vector对象vstd::vector<int> v;// 使用assign()函数给v分配5个元素,每个元素的值都是10v.assign(5, 10); //第二种用法std::cout << "The vector elements are: ";for(int i=0; i<v.size(); i++)std::cout << v[i] << " ";// 使用assign()将v的内容替换为2, 3v.assign({2, 3}); // 第三种用法std::cout << "\nThe vector elements are: ";for(int i=0; i<v.size(); i++)std::cout << v[i] << " ";return 0;
}
以上程序的输出将会是:
The vector elements are: 10 10 10 10 10
The vector elements are: 2 3
官方示例
// vector assign
#include <iostream>
#include <vector>int main ()
{std::vector<int> first;std::vector<int> second;std::vector<int> third;first.assign (7,100); // 7 ints with a value of 100std::vector<int>::iterator it;it=first.begin()+1;second.assign (it,first.end()-1); // the 5 central values of firstint myints[] = {1776,7,4};third.assign (myints,myints+3); // assigning from array.std::cout << "Size of first: " << int (first.size()) << '\n';std::cout << "Size of second: " << int (second.size()) << '\n';std::cout << "Size of third: " << int (third.size()) << '\n';return 0;
}Edit & run on cpp.sh
Output:
Size of first: 7
Size of second: 5
Size of third: 3