首页 > 代码库 > C++容器类对象函数参数问题

C++容器类对象函数参数问题

总之一句话:容器类对象作为函数参数,与整数类型作为函数参数的传递特性相同。

验证程序

#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;

void do_something1(list<int> *ls)
{
	ls->push_back(1);
	ls->push_back(2);
	ls->push_back(3);

	return;
}

void do_something2(list<int> ls)
{
	ls.push_back(1);
	ls.push_back(2);
	ls.push_back(3);

	return;
}

void do_something3(list<int> &ls)
{
	ls.push_back(1);
	ls.push_back(2);
	ls.push_back(3);

	return;
}

int main(void)
{
	list<int> ls1,ls2,ls3;
	
	cout<<"**************"<<endl;
	cout<<"ls1:"<<endl;
	cout<<ls1.size()<<endl;
	do_something1(&ls1);
	cout<<ls1.size()<<endl;

	cout<<"**************"<<endl;
	cout<<"ls2:"<<endl;
	cout<<ls2.size()<<endl;
	do_something2(ls2);
	cout<<ls2.size()<<endl;

	cout<<"**************"<<endl;
	cout<<"ls3:"<<endl;
	cout<<ls3.size()<<endl;
	do_something3(ls3);
	cout<<ls3.size()<<endl;

	system("pause");
	return 0;
}