Respuestas a los ejercicios de la quinta edición de C ++ Primer [Capítulo tres]

Respuestas del ejercicio de la quinta edición de C ++ Primer [Lista general]: https://blog.csdn.net/Dust_Evc/article/details/114334124

3.1

Sección 1.4.1:

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
	int sum = 0;
	for (int val = 1; val <= 10; ++val) sum += val;

	cout << "Sum of 1 to 10 inclusive is " << sum << endl;
	
	return 0;
}

Sección 2.6.2:

#include <iostream>
#include <string>
#include "exercise2_42.h"

using std::cin;
using std::cout;
using std::endl;
using std::cerr;

int main()
{
    Sales_data data1, data2;

    double price = 0;  

    cin >> data1.bookNo >> data1.units_sold >> price;
    
    data1.revenue = data1.units_sold * price;

    cin >> data2.bookNo >> data2.units_sold >> price;
    data2.revenue = data2.units_sold * price;

    if (data1.bookNo == data2.bookNo)
    {
        unsigned totalCnt = data1.units_sold + data2.units_sold;
        double totalRevenue = data1.revenue + data2.revenue;

        cout << data1.bookNo << " " << totalCnt
            << " " << totalRevenue << " ";
        if (totalCnt != 0)
            cout << totalRevenue / totalCnt << endl;
        else
            cout << "(no sales)" << endl;

        return 0;  
    }
    else
    {  
        cerr << "Data must refer to the same ISBN" << endl;
        return -1; 
    }
}

3.2

Lea en una línea a la vez:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::getline;

int main()
{
	string s;
	while (getline(cin,s))
	{
		cout << s << endl;
	}
	return 0;
}

Lea una palabra a la vez:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s;
	while (cin >> s)
	{
		cout << s << endl;
	}
	return 0;
}

3.3

Similar a la lectura de is >> s, el objeto de cadena ignora el espacio en blanco inicial y comienza desde el primer carácter real hasta que encuentra el siguiente espacio en blanco.
* Similar a la lectura de getline (is, s), el objeto de cadena leerá caracteres del flujo de entrada hasta que se encuentre un carácter de nueva línea.

3.4

Relativamente grande:

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		if (str1 == str2)
			cout << "The two strings are equal." << endl;
		else
			cout << "The larger string is " << ((str1 > str2) ? str1 : str2);
	}

	return 0;
}

Más extenso:

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		if (str1.size() == str2.size())
			cout << "The two strings have the same length." << endl;
		else
			cout << "The longer string is " << ((str1.size() > str2.size()) ? str1 : str2) << endl;
	}

	return 0;
}

3,5

Sin separar:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string result, s;
	while (cin >> s)
	{
		result += s;
	}
	cout << result << endl;

	return 0;
}

Apartado:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string result, s;
	while (cin >> s)
	{
		result += s + " ";
	}
	cout << result << endl;

	return 0;
}

3.6

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this is a string";			    
	for (auto &x : s)
	{
		x = 'X';
	}

	cout << s << endl;
	return 0;
}

3,7


#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this is a string";

	for (char x : s)
	{
		x = 'X';
	}

	cout << s << endl;
	return 0;
}

En lugar de reemplazar la cadena con X, se emite la cadena original "esta es una cadena".

3.8

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this is a string";

	decltype(s.size()) i = 0;
	while (i != s.size())
	{
		s[i] = 'X';
		++i;
	}
	cout << s << endl;
	for (i = 0; i != s.size(); ++i)
	{
		s[i] = 'Y';
	}
	cout << s << endl;
	return 0;
}

3.9

ilegal. El uso de subíndices para acceder a cadenas vacías es ilegal .

3.10

#include <iostream>
#include <string>
#include <cctype>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	string s = "this, is. a :string!";
	string result;

	for (auto x : s)
	{
		if (!ispunct(x))
		{
			result += x;
		}
	}

	cout << result << endl;
	return 0;
}

3.11

De acuerdo con el código en el bucle for para ver si es legal, c es una referencia a un carácter en el objeto de cadena y s es una constante. Por lo tanto, si el código en el ciclo for reasigna el valor de c, será ilegal, y si no se cambia el valor de c, será legal.

3.12

(a) Legal en C ++ 11 (b) Ilegal, diferentes tipos (c) Legal

3.13

vector <int> v1; // tamaño: 0,   sin valores.
vector <int> v2 (10); // tamaño: 10, valor: 0
vector <int> v3 (10, 42); // tamaño: 10, valor: 42
vector <int> v4 {10}; // tamaño: 1, valor: 10
vector <int> v5 {10, 42}; // tamaño: 2, valor: 10, 42
vector <cadena> v6 {10}; // tamaño: 10, valor: ""
vector <cadena> v7 {10, "hola"}; // tamaño: 10, valor: "hola"

3,14

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main()
{
	vector<int> v;
	int i;
	while (cin >> i)
	{
		v.push_back(i);
	}
	return 0;
}

3,15

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<string> v;
	string i;
	while (cin >> i)
	{
		v.push_back(i);
	}
	return 0;
}

3,16

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<int> v1;         // size:0,  no values.
	vector<int> v2(10);     // size:10, value:0
	vector<int> v3(10, 42); // size:10, value:42
	vector<int> v4{ 10 };     // size:1,  value:10
	vector<int> v5{ 10, 42 }; // size:2,  value:10, 42
	vector<string> v6{ 10 };  // size:10, value:""
	vector<string> v7{ 10, "hi" };  // size:10, value:"hi"

	cout << "v1 size :" << v1.size() << endl;
	cout << "v2 size :" << v2.size() << endl;
	cout << "v3 size :" << v3.size() << endl;
	cout << "v4 size :" << v4.size() << endl;
	cout << "v5 size :" << v5.size() << endl;
	cout << "v6 size :" << v6.size() << endl;
	cout << "v7 size :" << v7.size() << endl;

	cout << "v1 content: ";
	for (auto i : v1)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v2 content: ";
	for (auto i : v2)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v3 content: ";
	for (auto i : v3)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v4 content: ";
	for (auto i : v4)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v5 content: ";
	for (auto i : v5)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v6 content: ";
	for (auto i : v6)
	{
		cout << i << " , ";
	}
	cout << endl;

	cout << "v7 content: ";
	for (auto i : v7)
	{
		cout << i << " , ";
	}
	cout << endl;
	return 0;
}

3,17

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<string> v;
	string s;

	while (cin >> s)
	{
		v.push_back(s);
	}

	for (auto &str : v)			//str引用vector中各元素(这里各元素类型为String)
	{
		for (auto &c : str)		//c引用vector中各元素的各字符(这里类型为char)
		{
			c = toupper(c);		//将各字符转为大写
		}
	}

	for (auto i : v)		// 将vector中各元素内的String逐个输出
	{
		cout << i << endl;
	}
	return 0;
}

3,18

ilegal. Debería cambiarse a:

vector<int> ivec;
ivec.push_back(42);

3,19

Hay tres tipos:

vector<int> ivec1(10, 42);
vector<int> ivec2{ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
vector<int> ivec3;
for (int i = 0; i < 10; ++i)
	ivec3.push_back(42);

La primera forma es la mejor.

3,20

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<int> ivec;
	int i;
	while (cin >> i)
	{
		ivec.push_back(i);
	}
	cout << "相邻整数的和:" << endl;

	for (int i = 0; i < (ivec.size() - 1); ++i)
	{
		cout << ivec[i] + ivec[i + 1] << endl;
	}

	//---------------------------------
	cout << "---------------------------------" << endl;
	cout << "首位对称整数的和:" << endl;

	int m = 0;
	int n = ivec.size() - 1;
	while (m < n)
	{
		cout << ivec[m] + ivec[n] << endl;
		++m;
		--n;
	}
	return 0;
}

3,21

#include <vector>
#include <iterator>
#include <string>
#include <iostream>

using std::vector;
using std::string;
using std::cout;
using std::endl;

void check_and_print(const vector<int>& vec)
{
	cout << "size: " << vec.size() << "  content: [";
	for (auto it = vec.begin(); it != vec.end(); ++it)
		cout << *it << (it != vec.end() - 1 ? "," : "");
	cout << "]\n" << endl;
}

void check_and_print(const vector<string>& vec)
{

	cout << "size: " << vec.size() << "  content: [";
	for (auto it = vec.begin(); it != vec.end(); ++it)
		cout << *it << (it != vec.end() - 1 ? "," : "");
	cout << "]\n" << endl;
}

int main()
{
	vector<int> v1;
	vector<int> v2(10);
	vector<int> v3(10, 42);
	vector<int> v4{ 10 };
	vector<int> v5{ 10, 42 };
	vector<string> v6{ 10 };
	vector<string> v7{ 10, "hi" };

	check_and_print(v1);
	check_and_print(v2);
	check_and_print(v3);
	check_and_print(v4);
	check_and_print(v5);
	check_and_print(v6);
	check_and_print(v7);

	return 0;
}

3,22

#include <iostream>
#include <vector>
#include <cctype>
#include <string>

using namespace std;

int main()
{
	vector<string> text;
	text.push_back("aaaaaaaaaa aaaaaaaaa aaaaaa");
	text.push_back("");
	text.push_back("bbbbbbbbbbbbbb bbbbbbbbbbb bbbbbbbbbbbbb");

	for (auto it = text.begin(); it != text.end() && !it->empty(); ++it)
	{
		for (auto &c : *it)
		{
			c = toupper(c);
		}
	}

	for (auto it : text)
	{
		cout << it << endl;
	}
	return 0;
}

3,23

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> ivec(10, 30);

	for (auto &it : ivec)
	{
		it = it * 2;
		cout << it << endl;
	}

	return 0;
}

3,24

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<int> ivec;
	int i;
	while (cin >> i)
	{
		ivec.push_back(i);
	}
	cout << "相邻整数的和:" << endl;

	for (auto it = ivec.begin(); it != ivec.end() - 1; ++it)
	{
		cout << *it + *(it + 1) << endl;
	}

	//---------------------------------
	cout << "---------------------------------" << endl;
	cout << "首位对称整数的和:" << endl;

	auto it1 = ivec.begin();
	auto it2 = ivec.end() - 1;
	while (it1 < it2)
	{
		cout << *it1 + *it2 << endl;
		++it1;
		--it2;
	}
	return 0;
}

3,25

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

int main()
{
	vector<unsigned > scores;  //类型unsigned int 可以缩写为unsigned
	vector<unsigned > grade(11, 0);
	unsigned  i;
	while (cin >> i)    //原数据为:42 65 95 100 39 67 95 76 88 76 83 92 76 93
	{
		scores.push_back(i);
	}

	cout << "各成绩对应的分段为:";
	for (auto it = scores.begin(); it != scores.end(); ++it)
	{
		if (*it <= 100)
		{
			++grade[*it / 10];
			cout << *it / 10 << (it != scores.end() - 1 ? " " : "");
		}		
	}
	cout << endl;

	cout << "各分段总数为:";
	for (auto cnt : grade)
	{
		cout  << cnt << " ";
	}
	cout << endl;
	return 0;
}

3,26

Porque las operaciones admitidas por los iteradores son solo `-`, pero no` + ` . `end-beg` significa varios elementos separados, divídalo por 2 y agréguelo a mendigar, lo que significa mover mendigar a la mitad de la posición.

3,27

(a) Ilegal. La dimensión debe ser una expresión constante.
(b) Legal.
(c) ilegal. El valor de txt_size () no se puede obtener hasta el tiempo de ejecución y no puede ser negativo.
(d) Ilegal. El tamaño de la matriz debe ser 12.

3,28

Los elementos de la matriz se inicializarán de forma predeterminada.

Los valores de los elementos de sa son todos cadenas vacías y los valores de los elementos de ia son todos 0.

Los valores de los elementos de sa2 son cadenas vacías y los valores de los elementos de ia2 no están definidos .

3,29

El tamaño de la matriz está determinado; los
elementos no se pueden agregar de forma arbitraria;
no se permiten copias ni asignaciones.

3.30

Cuando ix aumenta a 10, el subíndice de ia [ix] está fuera de rango.

3.31

#include <vector>
#include <iostream>

int main()
{
	int arr[10];
	for (unsigned i = 0; i <= 9; ++i)
		arr[i] = i;	
	for (auto val : arr)
		std::cout << val << " ";
	std::cout << std::endl;
	return 0;
}

3.32

#include <iostream>
#include <vector>

using std::cout; 
using std::endl; 
using std::vector;

int main()
{
	// array
	int arr[10];
	for (int i = 0; i < 10; ++i) 
		arr[i] = i;
	int arr2[10];
	for (int i = 0; i < 10; ++i)  //数组需逐元素拷贝赋值
		arr2[i] = arr[i];	

	// vector
	vector<int> v(10);
	for (int i = 0; i < 10; ++i) 
		v[i] = arr[i];
	vector<int> v2(v);	//向量可以直接将v赋给v2
	for (auto i : v2) 
		cout << i << " ";
	cout << endl;

	return 0;
}

3.33

Si tiene este formato: puntuaciones sin firmar [11];
cada elemento de la matriz se inicializará de forma predeterminada en: 3435973836

3.34

Mueva p1 a la posición de p2. Es legal bajo cualquier circunstancia.

3.35

#include <iostream>

using std::cout;
using std::endl;

int main()
{
	const int size = 10;
	int arr[size];
	for (auto ptr = arr; ptr != arr + size; ++ptr) 
		*ptr = 0;

	for (auto i : arr) 
		cout << i << " ";
	cout << endl;

	return 0;
}

3.36

#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

bool compare(int* const pb1, int* const pe1, int* const pb2, int* const pe2)
{
	if ((pe1 - pb1) != (pe2 - pb2)) 
		return false;
	else
	{
		for (int* i = pb1, *j = pb2; (i != pe1) && (j != pe2); ++i, ++j)
		if (*i != *j) return false;
	}

	return true;
}

int main()
{
	int arr1[3] = { 0, 1, 2 };
	int arr2[3] = { 0, 2, 4 };

	if (compare(begin(arr1), end(arr1), begin(arr2), end(arr2)))
		cout << "The two arrays are equal." << endl;
	else
		cout << "The two arrays are not equal." << endl;

	cout << "==========" << endl;

	vector<int> vec1 = { 0, 1, 2 };
	vector<int> vec2 = { 0, 1, 2 };

	if (vec1 == vec2)
		cout << "The two vectors are equal." << endl;
	else
		cout << "The two vectors are not equal." << endl;

	return 0;
}

3.37

Imprimirá los elementos de la matriz de caracteres ca. Pero debido a que no hay un carácter nulo, el programa no saldrá del ciclo.

3.38

Restar dos punteros puede indicar la distancia entre los dos punteros (en la misma matriz) y agregar un número entero al puntero también puede indicar mover el puntero a una determinada posición. Pero la adición de dos punteros no tiene un significado lógico, por lo que no se pueden agregar dos punteros.

3.39

#include <iostream>
#include <string>

using std::cout; 
using std::endl; 
using std::string;

int main()
{
	string s1("aaaaaaaaaa"), s2("bbbbbbbbbb");
	if (s1 == s2)
		cout << "same string." << endl;
	else if (s1 > s2)
		cout << "aaaaaaaaaa > bbbbbbbbbb" << endl;
	else
		cout << "aaaaaaaaaa < bbbbbbbbbb" << endl;

	cout << "=========" << endl;

	const char* cs1 = "aaaaaaaaaa";
	const char* cs2 = "bbbbbbbbbb";
	auto result = strcmp(cs1, cs2);
	if (result == 0)
		cout << "same string." << endl;
	else if (result < 0)
		cout << "aaaaaaaaaa < bbbbbbbbbb" << endl;
	else
		cout << "aaaaaaaaaa > bbbbbbbbbb" << endl;

	return 0;
}

3,40

#include <iostream>
#include <cstring>

const char cstr1[] = "Hello";
const char cstr2[] = "world!";

int main()
{
	char cstr3[100];

	strcpy(cstr3, cstr1);
	strcat(cstr3, " ");
	strcat(cstr3, cstr2);

	std::cout << cstr3 << std::endl;
}

3,41

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	vector<int> v(begin(arr), end(arr));

	for (auto i : v) cout << i << " ";
	cout << endl;

	return 0;
}

3,42

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int arr[10];
	for (int i = 0; i != v.size(); ++i) 
		arr[i] = v[i];

	for (auto i : arr) cout << i << " ";
	cout << endl;

	return 0;
}

3,43

#include <iostream>

using std::cout;
using std::endl;

int main()
{
	int arr[3][4] =
	{
		{ 0, 1, 2, 3 },
		{ 4, 5, 6, 7 },
		{ 8, 9, 10, 11 }
	};

	// range for
	for (const int(&row)[4] : arr)
		for (int col : row) cout << col << " ";

	cout << endl;

	// for loop
	for (size_t i = 0; i != 3; ++i)
		for (size_t j = 0; j != 4; ++j) cout << arr[i][j] << " ";

	cout << endl;

	// using pointers.
	for (int(*row)[4] = arr; row != arr + 3; ++row)
		for (int *col = *row; col != *row + 4; ++col) cout << *col << " ";

	cout << endl;

	return 0;
}

3,44

#include <iostream>

using std::cout; 
using std::endl;

int main()
{
	int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

	using int_array = int[4];

	for (int_array& p : ia)
		for (int q : p)
			cout << q << " ";
	cout << endl;

	for (size_t i = 0; i != 3; ++i)
		for (size_t j = 0; j != 4; ++j)
			cout << ia[i][j] << " ";
	cout << endl;

	for (int_array* p = ia; p != ia + 3; ++p)
		for (int *q = *p; q != *p + 4; ++q)
			cout << *q << " ";
	cout << endl;

	return 0;
}

3,45

#include <iostream>

using std::cout;
using std::endl;

int main()
{
	int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

	for (auto& p : ia)
		for (auto q : p)
			cout << q << " ";
	cout << endl;

	for (auto i = 0; i != 3; ++i)
		for (auto j = 0; j != 4; ++j)
			cout << ia[i][j] << " ";
	cout << endl;

	for (auto p = ia; p != ia + 3; ++p)
		for (auto q = *p; q != *p + 4; ++q)
			cout << *q << " ";
	cout << endl;

	return 0;
}

 

Supongo que te gusta

Origin blog.csdn.net/Dust_Evc/article/details/114159821
Recomendado
Clasificación