下面是看书后写的几个小例子:
std::max
- #include <algorithm>
- #include <iostream>
- using namespace std;
- bool ptr(int* a, int* b) {
- return *a < *b;
- }
- int main() {
- int x = 11;
- int y = 12;
- cout << "max value: " << max(11, 12) << endl;
- int* px = &x;
- int* py = &y;
- cout << "max ptr value: " << *max(px, py, ptr) << endl;
- }
运行结果:
- max value: 12
- max ptr value: 12
std::swap练习
- #include <algorithm>
- #include <iostream>
- using std::cout;
- using std::endl;
- using std::ostream;
- class MyContainer {
- int* elems;
- int numElems;
- public:
- MyContainer(int * array, int num) {
- elems = array;
- numElems = num;
- }
- void swap(MyContainer& mc) {
- std::swap(elems, mc.elems);
- std::swap(numElems, mc.numElems);
- }
- friend ostream& operator<<(ostream&, const MyContainer&);
- };
- ostream& operator<<(ostream& os, const MyContainer& mc) {
- for(int i = 0; i < mc.numElems; ++i) {
- os << *(mc.elems + i) << " ";
- }
- // os << endl;
- return os;
- }
- inline void swap(MyContainer& c1, MyContainer& c2) {
- c1.swap(c2);
- }
- int main() {
- int a[10];
- int b[10];
- for(int i = 0; i < 10; ++i) {
- a[i] = i * i;
- b[i] = (9 -i) * (9 - i) * (9 - i);
- }
- MyContainer mc_a(a, 10);
- MyContainer mc_b(b, 10);
- cout << "before swap: " << endl;;
- cout << "mc_a: " << mc_a << endl;
- cout << "mc_b: " << mc_b << endl;
- swap(mc_a, mc_b);
- cout << "after swap: " << endl;
- cout << "mc_a: " << mc_a << endl;
- cout << "mc_b: " << mc_b << endl;
- }
运行结果:
- before swap:
- mc_a: 0 1 4 9 16 25 36 49 64 81
- mc_b: 729 512 343 216 125 64 27 8 1 0
- after swap:
- mc_a: 729 512 343 216 125 64 27 8 1 0
- mc_b: 0 1 4 9 16 25 36 49 64 81
std::rel_ops练习:
- #include <iostream>
- #include <utility>
- #include <string>
- using std::cout;
- using std::endl;
- using std::string;
- class name {
- string firstName;
- string lastName;
- public:
- name(const string& first,
- const string& last) {
- firstName = first;
- lastName = last;
- }
- bool operator==(const name& rhs) const {
- return (firstName == rhs.firstName &&
- lastName == rhs.lastName);
- }
- bool operator<(const name& rhs) const {
- return (firstName < rhs.firstName ||
- (firstName == rhs.firstName && lastName < rhs.lastName));
- }
- };
- int main() {
- using namespace std::rel_ops;
- name n1("John", "Brown");
- name n2("Henry", "Brown");
- cout << ((n1 > n2) ? "n1 is bigger than n2" : "n1 is smaller than n2") << endl;
- name n3("John", "Brown");
- cout << ((n3 != n1) ? "n3 is not equal to n1" : "n3 is equal to n1") << endl;
- }