第6章 数组 指针与字符串

1.编写并测试3*3矩阵(方阵)转置,用户输入数据,使用数组保存转置矩阵。

	int a[3][3];
	//用户输入
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < 3; j++)
			cin >> a[i][j];
	//转置
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < i; j++)
		{
			int temp;
			temp = a[j][i];
			a[j][i] = a[i][j];
			a[i][j] = temp;
		}
	//显示结果
	for (int i = 0; i < 3; i++)
	{
		cout << endl;
		for (int j = 0; j < 3; j++)
			cout << a[i][j]<<" ";
	}

输入样例:1,2,3                 输出结果:1,4,7                              

                  4,5,6                                   2,5,8

                  7,8,9                                   3,6,9  

2.使用动态内存分配生成动态数组来重新完成矩阵转置,使用指针实现函数的功能。

	//动态数组的创建
	int** a = new int*[3];
	for (int i = 0; i < 3; i++)
		a[i] = new int[3];

 数据的处理与问题一相同,输出结果也相同。

3.编程实现两个字符串的连接,使用字符数组保存字符串,不要使用系统函数。

//连接函数
void linkString(const char* head, const char* back, char* res)
{
	//保存初始指针位置
	char* start = res;
	//将前后的字符连接
	while (*head != '\0')
		*res++ = *head++;
	while (*back != '\0')
		*res++ = *back++;
	//存储字符串结束标志
	*res = '\0';
	//还原结果指针初始位置
	res = start;
}

int main()
{
	//测试样例
	const char* a = "abc", *b = "defg";
	char* res = new char[20];
	linkString(a, b, res);
	//输出结果
	while (*res != '\0')
		cout << *res++;
	return 0;
}

输出结果:abcdefg

4.使用string类声明字符串对象,重新实现字符串连接。

	//输入样例
	string a = "abc", b = "defg";
	//结果变量
	string res;
	//连接
	res = a + b;
	//输出结果
	cout << res;

输出结果:abcdefg

5.声明一个Employee类,包括姓名、街道、城市和邮编等属性,以及changeName()和display()等函数。Display()显示姓名、街道等属性,changeName()改变对象的姓名属性,实现该类,并测试。

class Employee
{
private:
	//类的所有属性
	string name,
		   street,
		   city,
		   mail;
public:
	//构造函数的实现
	Employee(string name, string street = "UNKOWN", string city = "UNKOWN", string mail = "UNKOWN") :name(name), street(street), city(city), mail(mail){}

	void changeName(string newName) { name = newName; }

	void display();
};
//显示函数实现
void Employee::display()
{
	cout << "name: " << name << endl;
	cout << "street: " << street << endl;
	cout << "city: " << city << endl;
	cout << "mail: " << mail << endl;
}
int main()
{

	Employee me("WangWei","ChangAn","BeiJing","00001");
	me.display();
	me.changeName("WW");
	cout << endl;
	me.display();
	return 0;
}

6.声明包含5个元素的对象数组,每个都是Employee的对象。

	Employee nameList[5];

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值