C++ Primer 课后习题 3.6
练习 3.43: 编写3个不同版本的程序,令其均能输出ia的元素。版本1使用范围 for 语句管理迭代过程;版本 2 和版本 3 都使用普通的 for 语句,其中版本 2 要求下标运算符,版本 3 要求用指针。此外,在所有 3 个版本中都要直接写出数据类型,而不能使用类型别名、auto 关键字或 decltype 关键字。
// ex_43.cc
#include <iostream>
int main() {
int ia[3][4] = {32, 44, 83, 64,
78, 21, 49, 55,
64, 40, 82, 27};
std::cout << "Use range for: " << std::endl;
// use range for
for (int (&p)[4] : ia) {
for (int q : p) {
std::cout << q << '\t';
}
std::cout << std::endl;
}
// use ordinary for and subscripts:
std::cout << "\nUse ordinary for and subscripts: " << std::endl;
for (size_t i = 0; i != 3; ++i) {
for (size_t j = 0; j != 4; ++j) {
std::cout << ia[i][j] << '\t';
}
std::cout << std::endl;
}
// use ordinary for and pointers:
std::cout << "\nUse ordinary for and pointers: " << std::endl;
for (int (*p)[4] = ia; p != ia + 3; ++p) {
for (int *q = *p; q != *p + 4; ++q) {
std::cout << *q << '\t';
}
std::cout << std::endl;
}
return 0;
}
$ ./ex_43.out
Use range for:
32 44 83 64
78 21 49 55
64 40 82 27
Use ordinary for and subscripts:
32 44 83 64
78 21 49 55
64 40 82 27
Use ordinary for and pointers:
32 44 83 64
78 21 49 55
64 40 82 27
练习 3.44: 改写上一个练习中的程序,使用类型别名来代替循环控制变量的类型。
// ex_44.cc
#include <iostream>
int main() {
int ia[3][4] = {32, 44, 83, 64,
78, 21, 49, 55,
64, 40, 82, 27};
typedef int (&ref_iarr)[4];
using int_arr = int[4];
using idx = size_t;
// use range for:
std::cout << "range for: " << std::endl;
for (ref_iarr row : ia) {
for (int col : row) {
std::cout << col << '\t';
}
std::cout << std::endl;
}
// use ordinary for and subscripts:
std::cout << "\nordinary for and subscripts: " << std::endl;
for (idx i = 0; i != 3; ++i) {
for (idx j = 0; j != 4; ++j) {
std::cout << ia[i][j] << '\t';
}
std::cout << std::endl;
}
// use ordinary for and pointers:
std::cout << "\nordinary for and pointers: " << std::endl;
for (int_arr *row = std::begin(ia); row != std::end(ia); ++row) {
for (int *col = std::begin(*row); col != std::end(*row); ++col) {
std::cout << *col << '\t';
}
std::cout << std::endl;
}
return 0;
}
$ ./ex_44.out
range for:
32 44 83 64
78 21 49 55
64 40 82 27
ordinary for and subscripts:
32 44 83 64
78 21 49 55
64 40 82 27
ordinary for and pointers:
32 44 83 64
78 21 49 55
64 40 82 27
练习 3.45: 再一次改写程序,这次使用 auto 关键字。
// ex_45.cc
#include <iostream>
int main() {
int ia[3][4] = {32, 44, 83, 64,
78, 21, 49, 55,
64, 40, 82, 27};
std::cout << "range for: " << std::endl;
for (auto &row : ia) {
for (auto col : row) {
std::cout << col << '\t';
}
std::cout << std::endl;
}
// std::cout << "\nordinary for and subscripts: " << std::endl;
std::cout << "\nordinary for and pointers: " << std::endl;
for (auto row = std::begin(ia); row != std::end(ia); ++row) {
for (auto col = std::begin(*row); col != std::end(*row); ++col) {
std::cout << *col << '\t';
}
std::cout << std::endl;
}
return 0;
}
$ ./ex_45.out
range for:
32 44 83 64
78 21 49 55
64 40 82 27
ordinary for and pointers:
32 44 83 64
78 21 49 55
64 40 82 27