list容器的基本操作

#include "iostream"
using namespace std;
#include "vector"

class Teacher                     
{
private:
	int age;
	char  *name;
public:
	Teacher(int age = 0, char *name = NULL)
	{
		int n = strlen(name);
		cout << "n = " << n << endl;
		if (name != NULL)
		{
			this->name = new char[n + 1];
			strcpy(this->name, name);
		}
		this->age = age;
	}

/*
	~Teacher()
	{
		if (this->name != NULL)
		{
			cout << "析构函数" << endl;
			delete[] name;
			this->name = NULL;
			age = 0;
		}
		
	}

*/
	Teacher(const Teacher &obj)                   //拷贝构造函数
	{
		this->name = NULL;
		this->name = new char[strlen(obj.name)];
		strcpy(this->name, obj.name);
		this->age = obj.age;
	}

	void print()
	{
		cout << "name = " << name << endl;
		cout << "age = " << age << endl;
	}
};

// 在下面的main函数中,v1.begin() 指在 1, 而v1.end() 指在10 的后面
void in11()           //遍历容器
{
	vector<int> v1(10);
	for (int i = 0; i < 10; i++)
	{
		v1[i] = i + 1;
	}

	for (vector<int> ::iterator it = v1.begin(); it != v1.end(); it++)         //正向遍历
	{
		cout << *it << " ";
	}
	cout << endl;

	for (vector<int> ::reverse_iterator rit = v1.rbegin(); rit != v1.rend(); rit++)
	{
		cout << *rit << " ";
	}
	cout << endl;
}

void playobj( Teacher &const obj)
{
	obj.print();
}

void printV(vector <char> &v1)
{
	for (vector<char> ::iterator it = v1.begin(); it != v1.end(); it++)         //正向遍历
	{
		cout << *it << " ";
	}
	cout << endl;
}


void main()
{
	Teacher t1(23, "zwt");
	Teacher t2(22, "lqm");
	Teacher t3(21, "lqms");

	playobj(t1);

	Teacher t4 = t2;
	playobj(t4);
	vector <Teacher> v1;
	v1.push_back(t1); 
	v1.push_back(t2);
	v1.push_back(t3);
	cout << v1.size() << endl;



	for (vector<Teacher> ::iterator it = v1.begin(); it != v1.end(); it++)
	{
		(*it).print();
	}
	
	cout << "hello. . ." << endl;
	system("pause");
}



void main11()           // 插入和删除
{
	vector<char> v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back('a' + i);
	}
	v1.push_back('\0');
	for (int i = 0; i < 10; i++)
	{
		cout << v1[i];
	}
	cout << endl;

	//v1.erase(v1.begin(), v1.begin() + 3);              //区间删除
	//for (int i = 0; i < v1.size(); i++)
	//{
	//	cout << v1[i];
	//}
	//cout << endl;

	v1[5] = 'a';
	v1[6] = 'a';
	for (vector<char> ::iterator it = v1.begin(); it != v1.end(); it++)         //正向遍历
	{
		cout << *it<<" ";
	}
	cout << endl;

	for (vector<char> ::iterator it = v1.begin(); it != v1.end();   )         //正向遍历  删除是 a 的元素
	{
		if (*it == 'a')
		{
			it = v1.erase(it);
		}
		else
		{
			it++;
		}
	}

	printV(v1);
	cout << "--------------" << endl;

	v1.insert(v1.begin(), 'A');
	v1.insert(v1.end() , 'B');
	printV(v1);


	system("pause");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值