6.10 编写一个函数,使用指针(引用)形参交换两个整数的值
#include <iostream>
#include <string>
using namespace std;
void swap(int &num1, int &num2)
{
int tmp;
tmp = num1;
num1 = num2;
num2 = tmp;
}
int main()
{
cout << "please input two number: " << endl;
int num1,num2;
cin>>num1>>num2;
cout << "before switch: " << num1 << " " << num2 << endl;
swap(num1, num2);
cout << "after switch: " << num1 << " " << num2 << endl;
system("pause");
return 0;
}
6.17 编写一个函数,判断string对象中是否有大写字母。编写另一个函数,把string对象全部改成小写形式。注意两个函数的形参的区别。
#include <iostream>
#include <string>
using namespace std;
bool any_capital(string const &str)
{
for (auto ch : str)
{
if (isupper(ch))
return true;
}
return false;
}
void to_lowercase(string &str)
{
for (auto &ch : str)
ch = tolower(ch);
}
int main()
{
string hello("Hello World!");
cout << any_capital(hello) << endl;
to_lowercase(hello);
cout << hello << endl;
system("pause");
return 0;
}
6.21 编写函数,令其接受两个参数:一个是int型的数,另一个是int指针。函数比较int值和int指针所指的值,返回较大者。
#include <iostream>
#include <string>
using namespace std;
int larger_one(const int i, const int *const p)
{
return (i > *p) ? i : *p;
}
int main()
{
int i = 6;
cout << larger_one(7, &i) << endl;
system("pause");
return 0;
}
6.22 编写函数,交换两个int指针
#include <iostream>
#include <string>
using namespace std;
void swap(int* &num1, int* &num2)
{
auto tmp = num1;
num1 = num2;
num2 = tmp;
}
int main()
{
int i = 42, j = 99;
auto num1 = &i;
auto num2 = &j;
std::cout << "before switching: " << *num1 << " " << *num2 << std::endl;
swap(num1, num2);
std::cout << "after switching: " << *num1 << " " << *num2 << std::endl;
std::cout << "after switching i j: " << i << " " << j << std::endl;
system("pause");
return 0;
}
## 6.23 使用几个print函数依次打印数组
```cpp
#include <iostream>
#include <string>
using namespace std;
void print(const int *pi)
{
if(pi)
cout << *pi << endl;
}
void print(const char *p)
{
if (p)
while (*p) cout << *p++;
cout << endl;
}
void print(const int *beg, const int *end)
{
while (beg != end)
cout << *beg++ << endl;
}
void print(const int ia[], size_t size)
{
for (size_t i = 0; i != size; ++i) {
cout << ia[i] << endl;
}
}
void print(int (&arr)[2])
{
for (auto i : arr)
cout << i << endl;
}
int main()
{
int i = 0, j[2] = { 0, 1 };
char ch[5] = "pezy";
print(ch);
print(begin(j), end(j));
print(&i);
print(j, end(j)-begin(j));
print(j);
system("pause");
return 0;
}