1. 程式人生 > >C++中map和vector作形參時如何給定預設引數?

C++中map和vector作形參時如何給定預設引數?

      之前遇到過這種特殊場景, 我用static變數比較噁心地解決了問題, 其實, 有更優雅的方式:

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

int main ()
{
	int a = int();
	cout << a << endl;
	
	vector<int> v = vector<int>();
	for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
	{
		cout << *it << endl;
	}
	
	return 0;
}

     看下: 

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

void fun(int a, int b = 1, const vector<int> &v=vector<int>()) // 此處的const不能少,v也必須初始化(因為左邊引數已經預設初始化)
{
	
}

int main ()
{
	fun(1);
	cout << "to end" << endl;
	
	return 0;
}

     不多說。