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

vector之assign 2020/12/15

程序员文章站 2022-03-22 22:16:58
...

先看原型:
void assign(size_type count, value_type val);

template
void assign(InIt first, InIt last);

共有三个函数重载,第三个咱也看不懂,不知道咋用,就不写了。

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

void main()
{
	vector < int > m_vc1{1, 2, 3, 4, 5, 6};
	cout << "m_vc1的元素:\n";
	for (auto node : m_vc1)
	{
		cout << node << " ";
	}
	cout << endl;

	cout << "m_vc2的元素:\n";
	vector<int> m_vc2;
	m_vc2.assign(6, 8);//6个100,共六个元素

	for_each(m_vc2.begin(), m_vc2.end(), [](int a){cout << a << " "; });
	cout << endl;

	vector<int> m_vc3;
	m_vc3.assign(m_vc1.begin(), m_vc1.end()-1);//比m_vc1少一个元素,也是是5个

	cout << "m_vc3的元素:\n";
	for_each(m_vc3.begin(), m_vc3.end(), [](int a){cout << a << " "; });
	cout << endl;

	m_vc2.assign(m_vc1.begin(), m_vc1.end() - 2);//比m_vc1少一个元素,也是是4个
	cout << "m_vc2的元素:\n";
	for_each(m_vc2.begin(), m_vc2.end(), [](int a){cout << a << " "; });
	cout << endl;

	system("pause");
}

结果:
vector之assign 2020/12/15

相关标签: C/C++基础