assign函数
语法:
1 2 3 4 |
1.迭代器方式 template<typename _InputIterator> void assign(_InputIterator __first, _InputIterator __last); 2.个数,值 void assign(size_type __n, const value_type& __val) |
assign() 对Vector中的元素赋值
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
/** * @brief Assigns a given value to a %vector. * @param n Number of elements to be assigned. * @param val Value to be assigned. * * This function fills a %vector with @a n copies of the given * value. Note that the assignment completely changes the * %vector and that the resulting %vector's size is the same as * the number of elements assigned. Old data may be lost. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %vector. * @param first An input iterator. * @param last An input iterator. * * This function fills a %vector with copies of the elements in the * range [first,last). * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. Old data may be lost. */ template<typename _InputIterator> void assign(_InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_assign_dispatch(__first, __last, _Integral()); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1(10, 0); vector<int> v2(10, 2); //void assign(size_type __n, const value_type& __val) v1.assign(5,8); for(int i=0;i<v1.size();i++){ cout<<v1[i]<<","; } cout<<endl; //template<typename _InputIterator> //void assign(_InputIterator __first, _InputIterator __last) v2.assign(v1.begin(),v1.end()); for(int i=0;i<v2.size();i++){ cout<<v2[i]<<","; } cout<<endl; } |
测试结果:
1 2 |
8,8,8,8,8, 8,8,8,8,8, |