向量::赋值() 是一个C++中的STL,它通过替换旧元素来给向量元素赋值。如有必要,它还可以修改向量的大小。
null
分配常量值的语法:
vectorname.assign(int size, int value)Parameters: size - number of values to be assignedvalue - value to be assigned to the vectorname
程序1:下面的程序展示了如何给向量赋值
CPP
// CPP program to demonstrate // how to assign constant values to a vector #include <bits/stdc++.h> using namespace std; int main() { vector< int > v; v.assign(7, 100); cout << "Size of first: " << int (v.size()) << '' ; cout << "Elements are" ; for ( int i = 0; i < v.size(); i++) cout << v[i] << endl; return 0; } |
输出
Size of first: 7Elements are100100100100100100100
从数组或列表中赋值的语法:
vectorname.assign(arr, arr + size)Parameters: arr - the array which is to be assigned to a vectorsize - number of elements from the beginning which has to be assigned.
程序2:下面的程序展示了如何从数组或列表中赋值
CPP
// CPP program to demonstrate // how to assign values to a vector // from a list #include <bits/stdc++.h> using namespace std; int main() { vector< int > v1; int a[] = { 1, 2, 3 }; // assign first 2 values v1.assign(a, a + 2); cout << "Elements of vector1 are" ; for ( int i = 0; i < v1.size(); i++) cout << v1[i] << " " ; vector< int > v2; // assign first 3 values v2.assign(a, a + 3); cout << "Elements of vector2 are" ; for ( int i = 0; i < v2.size(); i++) cout << v2[i] << " " ; return 0; } |
输出
Elements of vector1 are1 2 Elements of vector2 are1 2 3
用于修改向量值的语法
vectorname.assign(InputIterator first, InputIterator last) Parameters: first - Input iterator to the initial position range.last - Input iterator to the final position range.
程序3:下面的程序显示了如何修改向量
CPP
// CPP program to demonstrate // how to modify vector size #include <bits/stdc++.h> using namespace std; int main() { vector< int > v; v.assign(7, 100); cout << "Size of first: " << int (v.size()) << '' ; cout << "Elements are" ; for ( int i = 0; i < v.size(); i++) cout << v[i] << endl; // modify the elements v.assign(v.begin(), v.begin() + 3); cout << "Modified VectorElements are" ; for ( int i = 0; i < v.size(); i++) cout << v[i] << endl; return 0; } |
输出
Size of first: 7Elements are100100100100100100100Modified VectorElements are100100100
使用初始值设定项列表赋值的语法:
vectorname.assign((initializer_list)Parameter: initializer_list
程序4:下面的程序显示了如何使用初始值设定项列表分配向量。
C++
#include <iostream> #include <vector> using namespace std; int main() { vector< int > v; // Initialize v with an initialization list v.assign({ 1, 2, 3 }); cout << "The list is:" << endl; for ( auto i = v.begin(); i != v.end(); i++) { // Printing 1 2 3 as output cout << *i << " " ; } return 0; } |
输出
The list is:1 2 3
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END