4-21
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vint;
const int sz = 100;
cout << "原向量:" << endl;
for (int i = 0; i < sz; i++) {
vint.push_back(i);
cout << i << " ";
}
cout << endl;
cout << "新向量:" << endl;
for (auto &i : vint) {
i = i % 2 != 0 ? i * 2 : i;
cout << i << " ";
}
cout << endl;
system("pause");
}
4-22
#include<iostream>
#include<string>
using namespace std;
int main()
{
string result;
unsigned int grade;
while (cin >> grade) {
if (grade <= 100) {
result = grade >= 90 ? "high pass" : grade >= 75 ? "pass" :
grade >= 60 ? "low pass" : "failure";
cout << "条件表达式:" << result << endl;
if (grade >= 90) {
result = "high pass";
}
else if (grade >= 75) {
result = "pass";
}
else if (grade >= 60) {
result = "low pass";
}
else {
result = "failure";
}
cout << "分支结构:" << result << endl;
}
}
system("pause");
}
4-28
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "short:\t\t" << sizeof(short) << endl;
cout << "int:\t\t" << sizeof(int) << endl;
cout << "long:\t\t" << sizeof(long) << endl;
cout << "long long:\t" << sizeof(long long) << endl;
cout << "char:\t\t" << sizeof(char) << endl;
cout << "wchar_t:\t" << sizeof(wchar_t) << endl;
cout << "char16_t:\t" << sizeof(char16_t) << endl;
cout << "char32_t:\t" << sizeof(char32_t) << endl;
cout << "bool:\t\t" << sizeof(bool) << endl;
cout << "float:\t\t" << sizeof(float) << endl;
cout << "double:\t\t" << sizeof(double) << endl;
cout << "long double:\t" << sizeof(long double) << endl;
system("pause");
}
4-37
把旧式的类型转换改成命名强制类型转换比较简单,观察转换前后的类型即可,如果涉及到类型变化就用static_cast<>(),如果涉及到去掉底层const就使用const_cast<>()。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
double d;
const string *ps;
char *pc;
void *pv;
//pv = (void*)ps;
pv = static_cast<void*>(const_cast<string*>(ps));
//i = int(*pc);
i = static_cast<int>(*pc);
//pv = &d;
pv = static_cast<void*>(&d);
//pc = (char*) pv;
pc = static_cast<char*>(pv);
system("pause");
}