本文共 2433 字,大约阅读时间需要 8 分钟。
c ++ assign函数
vector::assign() is a library function of "vector" header, it is used to initialize a vector or assign content to a vector, it assigns the new content to the vector, update the existing content, and also resizes the vector's size according to the content.
vector :: assign()是“ vector”标头的库函数,用于初始化矢量或将内容分配给矢量,将新内容分配给矢量,更新现有内容,并调整矢量的大小根据内容。
Note: To use vector, include <vector> header.
注意:要使用向量,请包含<vector>标头。
Syntax of vector::assign() function
vector :: assign()函数的语法
vector::assign(iterator_first, iterator_last); vector::assign(size_type n, value_type value);
Parameter(s):
参数:
In case of type 1: iterator_first, iterator_last – are the first and last iterators of a sequence with them we are going to assign the vector.
In case of type 2: n – is the size of the vector and value – is a constant value to be assigned.在类型1的情况下, iterator_first和iterator_last –是序列的第一个和最后一个迭代器,我们将为其分配向量。
对于类型2: n –是向量的大小,而value –是要分配的常数。Return value: void – In both of the cases it returns nothing.
返回值: void –在两种情况下均不返回任何内容。
Example:
例:
Input: vector v1; vector v2; //assigning v1.assign(5, 100); v2.assign(v1.begin(), v1.end()); Output: //if we print the value v1: 100 100 100 100 100 v2: 100 100 100 100 100
//C++ STL program to demonstrate example of//vector::assign() function#include#include using namespace std;int main(){ //declaring vectors vector v1; vector v2; vector v3; //an array that will be used to assign a vector int arr[] = { 10, 20, 30, 40, 50 }; //assigning vectors //assigning v1 with 5 elements and 100 as default value v1.assign(5, 100); //assigning v1 with array v2.assign(arr + 0, arr + 5); //assigning v3 with vector v2 v3.assign(v2.begin(), v2.end()); //pritning the vectors cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; cout << "v2: "; for (int x : v2) cout << x << " "; cout << endl; cout << "v3: "; for (int x : v3) cout << x << " "; cout << endl; return 0;}
Output
输出量
v1: 100 100 100 100 100v2: 10 20 30 40 50v3: 10 20 30 40 50
Reference:
参考:
翻译自:
c ++ assign函数
转载地址:http://xsvzd.baihongyu.com/