1. 程式人生 > 其它 >vector之assign 2020/12/15

vector之assign 2020/12/15

技術標籤:C/C++基礎

先看原型:
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"); }

結果:
在這裡插入圖片描述