欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

STL中vector的assign()函数用法

程序员文章站 2022-03-01 23:19:33
...

参考:

  1. https://blog.csdn.net/qq_45893475/article/details/120250105
  2. https://blog.csdn.net/doubleintfloat/article/details/52280481?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link

一、assign函数原型:

void assign(const_iterator first,const_iterator last);
void assign(size_type n,const T& x = T());

功能:

  1. 第一个相当于拷贝函数,把first到last的值赋值给调用者,注意区间的闭合,即:将区间 [first,last) 的元素赋值到当前的 vector 容器中;
  2. 第二个是把n个x赋值给调用者,即:赋 n 个值为 x 的元素到 vector 容器中,并且清除掉 vector 容器中以前的内容。

二、示例:

#include <vector>
#include <iostream>
using namespace std;

int main() {
 	vector<int> v1, v2, v3;
 	vector<int>::iterator iter;
 	v1.push_back(10);
 	v1.push_back(20);
 	v1.push_back(30);
 	v2.push_back(1);
 	v2.push_back(2);
    
 	cout << "v1 = " ;
 	for (iter = v1.begin(); iter != v1.end(); iter++)
  		cout << *iter << " ";
 	cout << endl;
    
	cout << "v2 = ";
 	for (iter = v2.begin(); iter != v2.end(); iter++)
  		cout << *iter << " ";
 	cout << endl;
	
    /*v2 = v1;
 	cout << "v2 = ";
 	for (iter = v2.begin(); iter != v2.end(); iter++)
  		cout << *iter << " ";
 	cout << endl;*/
 	
    v2.assign(v1.begin(), v1.end());
    cout << "v2 = ";
 	for (iter = v2.begin(); iter != v2.end(); iter++)
  		cout << *iter << " ";
 	cout << endl;
 	
    v3.assign(7, 3) ;
 	cout << "v3 = ";
 	for (iter = v3.begin(); iter != v3.end(); iter++)
  		cout << *iter << " ";
 	cout << endl;
    
 	return 0;
}
#include<iostream>
#include<vector>
using namespace std;

int main()
{
	vector<int>ls;
	vector<int>ls1;

	for(int i=0; i<20; ++i)
	{
		ls.push_back(i);
	}
	vector<int>::iterator lr = ls.begin();
	for(; lr != ls.end(); ++lr)
	{
		cout<<*lr<<" ";
	}
	cout<<endl;
	ls1.assign(ls.begin(),ls.begin()+9);

	for(lr = ls1.begin(); lr !=ls1.end(); ++lr)
	{
		cout<<*lr<<" ";
	}
	cout<<endl;
	
	ls.assign(10,7);
	for(lr = ls.begin(); lr !=ls.end(); ++lr)
	{
		cout<<*lr<<" ";
	}
	cout<<endl;
	return 0;
}

输出结果:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8
7 7 7 7 7 7 7 7 7 7
相关标签: c++ 开发语言