版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qit1314/article/details/90114839
书中页数:P131
代码名称:incr.cc vec_init.cc oofe.cc
//incr.cc
#include <iostream>
using std::cout; using std::endl;
int main()
{
int i = 0, j;
j = ++i; // j = 1, i = 1: prefix yields the incremented value
cout << i << " " << j << endl;
j = i++; // j = 1, i = 2: postfix yields the unincremented value
cout << i << " " << j << endl;
return 0;
}
//vec_init.cc
#include <cstddef>
using std::size_t;
#include <vector>
using std::vector;
#include <iostream>
using std::cout; using std::endl;
int main()
{
vector<int> ivec; // empty vector
int cnt = 10;
// add elements 10 . . . 1 to ivec
while (cnt > 0)
ivec.push_back(cnt--); // int postfix decrement
auto iter = ivec.begin();
// prints 10 9 8 . . . 1
while (iter != ivec.end())
cout << *iter++ << endl; // iterator postfix increment
vector<int> vec2(10, 0); // ten elements initially all 0
cnt = vec2.size();
// assign values from size . . . 1 to the elements in vec2
for(vector<int>::size_type ix = 0;
ix != vec2.size(); ++ix, --cnt)
vec2[ix] = cnt;
iter = vec2.begin();
// prints 10 9 8 . . . 1
while (iter != vec2.end())
cout << *iter++ << endl; // iterator postfix increment
return 0;
}
//oofe.cc
#include <cstddef>
using std::size_t;
#include <iostream>
using std::cout; using std::endl;
#include <string>
using std::string;
#include <cctype>
using std::toupper;
// chapter 6 will explain functions
// tolower and toupper change the argument itself, not a local copy
string &tolower(string &s)
{
for (auto &i : s)
i = tolower(i);
return s;
}
string &toupper(string &s)
{
for (auto &i : s)
i = toupper(i);
return s;
}
int main()
{
int i = 0;
cout << i << " " << ++i << endl; // undefined
string s("a string"), orig = s;
cout << toupper(s) << endl; // changes s to uppercase
cout << tolower(s) << endl; // changes s to lowercase
s = orig;
// the calls to toupper and tolower change the value of s
// << doesn't guarantee order of evaluation,
// so this expression is undefined
cout << toupper(s) << " " << tolower(s) << endl;
string first = toupper(s); // we control the order of evaluation
string second = tolower(s); // by storing the results in the order in which we want
cout << first << " " << second << endl; // one possible evaluation
cout << second << " " << first << endl; // equally legal evaluation!
cout << first << " " << first << endl; // another legal evaluation!
cout << second << " " << second << endl; // and a fourth!
return 0;
}