欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++primer 习题及答案分享

程序员文章站 2024-03-31 08:24:28
4.7编写代码实现一个数组赋值给另外一个数组,然后将这段代码改用vector实现。考虑如何将一个vector 赋值给另一个vector。 int main() { in...

4.7编写代码实现一个数组赋值给另外一个数组,然后将这段代码改用vector实现。考虑如何将一个vector 赋值给另一个vector。

int main()
{
	int a[3] = { 1,2,3 };
	int b[3];
	cout << "array :" << endl;
	for (int i = 0; i < 3; i++)
	{
		b[i] = a[i];
		cout << b[i] << endl;
	}
	

	vector ivec1 = { 1, 2, 3 };
	cout << "ivec1:" << endl;
	for (vector::iterator iter = ivec1.begin(); iter != ivec1.end(); ++iter)
	{
		cout <<*iter<< endl;
	}
	
	vectorivec2(ivec1);
	vector vec;
	vec = ivec2;
	cout << "ivec2:" << endl;
	for (vector::iterator iter = ivec2.begin(); iter != ivec2.end(); ++iter)
	{
		cout << *iter << endl;
	}
	cout << "vec:" << endl;
	for (vector::iterator iter = vec.begin(); iter != vec.end(); ++iter)
	{
		cout << *iter << endl;
	}
	return 0;

}

4.8 编写程序判断两个数组是否相等,然后编写一段类似的程序比较两个vector。

int main()
{
	int a[3] = { 1, 2, 3 };
	int b[3] = { 1, 2, 3 };
	cout << "use array:" << endl;
	if (sizeof(a) / sizeof(int) == sizeof(b) / sizeof(int))
	{
		size_t i = 0;
		for (i; i < sizeof(a) / sizeof(int); ++i)
		{
			if (a[i] != b[i])
			{
				cout << "两数组不相等" << endl;
				break;
			}
		}
		if (sizeof(a) / sizeof(int) == i)
		{
			cout << "两数组相等" << endl;
		}
	}
	cout << "use vector :" << endl;
	vector vec = { 1, 2, 3, 4 };
	vector vec2 = { 1, 2, 3, 4 };
		if (vec == vec2){
			cout << "两数组相等" << endl;
		}
		else
			cout << "两数组不相等" << endl;
	return 0;

}

4.9 编写程序定义一个有10个int型元素的数组,并以其在数组中的位置作为各元素的初值。

int main()
{
	int a[10];
	for (int i = 0; i < 10; ++i){
		a[i] = i;
		cout << a[i] << endl;
	}
	
	cout << "use vector" << endl;
	vector vec;
	for (int i = 0; i < 10; ++i){
		vec.push_back(i);
	}
	for (vector::iterator iter = vec.begin(); iter != vec.end(); ++iter){
		cout << *iter << endl;
	}

	return 0;

}

4.14 编写代码修改指针的值,然后在编写代码修改指针所指对象的值。

int main()
{
	int a (1),c(2);

	int *b = &a;
	b = &c;
	*b = 6;
	return 0;

}

4.16 下列程序实现什么功能?

int main()
{
	int i = 42, j = 1024;
	int *p1 = &i, *p2 = &j;
	*p2 = *p1 * *p2;
	*p1 *= *p1;
	cout << *p1 << "   "<<*p2 << endl;
	return 0;

}

4.18 编写一个程序,使用指针把一个int型数组的所有元素设置成0。

int main()
{
	int  a[3] = { 1, 2, 3 };
	
	for (int *p = a; p != a + 3; ++p){
		*p = 0;
	}
	for (int i = 0; i < 3; ++i){
		cout << a[i] << endl;
	}

}

4.25 编写程序比较两个string字符串,然后编写程序比较两个C风格字符串。

int main()
{
	cout << "C++ style!" << endl;
	string str1 = "hello world";
	string str2 = "good well";
	if (str1 == str2){
		cout << "两字符串相等" << endl;
	}
	else
		cout << "两字符串不相等" << endl;

	cout << "C style!" << endl;
	char ch1[] = "hello world";
	char ch2[] = "good well";
	if (!strcmp(ch1, ch2)){
		cout << "两字符串相等" << endl;
	}
	else
		cout << "两字符串不相等" << endl;

}