C++ STL 分配器

分配器

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. // 分配器
  5. const int NUM = 5;
  6. void useVector(){
  7. vector<int> rating(NUM);
  8. vector<double > titles(NUM);
  9. cout << "You will do ecactly as told. You will enter\n" << NUM << "book titles and your rating(0-10).\n";
  10. for (int i = 0; i < NUM; i++) {
  11. cout << "Enter title # " << i + 1 << ": ";
  12. cin >> titles[i];
  13. cout << "Enter your rating (0-10): ";
  14. cin >> rating[i];
  15. cin.get();
  16. }
  17. cout << "Thank you. You entered the following: \n" << "Rating\tBook\n";
  18. for (int i = 0; i < NUM; i++) {
  19. cout << rating[i] << "\t" << titles[i] << endl;
  20. }
  21. }
  22. int main() {
  23. useVector();
  24. return 0;
  25. }

STL函数的用法

  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. // STL函数的用法
  5. struct Review{
  6. string title;
  7. int rating;
  8. };
  9. bool operator<(const Review & r1, const Review & r2);
  10. bool worseThan(const Review & r1, const Review & r2);
  11. bool FillReview(Review & rr);
  12. void ShowReview(const Review & rr);
  13. bool operator<(const Review & r1, const Review & r2){
  14. if (r1.title < r2.title)
  15. return true;
  16. else if (r1.title == r2.title && r1.rating < r2.rating)
  17. return false;
  18. else
  19. return false;
  20. }
  21. bool worseThan(const Review & r1, const Review & r2){
  22. if (r1.rating < r2.rating)
  23. return true;
  24. else
  25. return false;
  26. }
  27. bool FillReview(Review & rr){
  28. cout << "Enter book title(quit to quit): ";
  29. getline(cin, rr.title);
  30. if (rr.title == "quit")
  31. return false;
  32. cout << "Enter book rating: ";
  33. cin >> rr.rating;
  34. if (!cin)
  35. return false;
  36. cin.get();
  37. return true;
  38. }
  39. void ShowReview(const Review & rr){
  40. cout << rr.rating << "\t" << rr.title << endl;
  41. }
  42. void stlFunction(){
  43. vector<Review> books;
  44. Review temp;
  45. while (FillReview(temp))
  46. books.push_back(temp);
  47. cout << "Thanks ,you entered the following " << books.size() << " rating:\n" << "Rating\tBook\n";
  48. for_each(books.begin(), books.end(), ShowReview);
  49. sort(books.begin(), books.end());
  50. cout << "Sorted by title : \nRating\tBook\n";
  51. for_each(books.begin(), books.end(), ShowReview);
  52. sort(books.begin(), books.end(), worseThan);
  53. cout << "Sorted by rating : \nRating\tBook\n";
  54. for_each(books.begin(), books.end(), ShowReview);
  55. cout << "Bye.\n";
  56. }
  57. int main() {
  58. stlFunction();
  59. return 0;
  60. }

迭代器的使用

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. using namespace std;
  5. // 迭代器
  6. void useIterator(){
  7. int casts[10] = {6, 7, 2, 9, 4, 11, 8, 7, 10, 5};
  8. vector<int > dice(10);
  9. // copy from to vector
  10. copy(casts, casts + 10, dice.begin());
  11. cout << "Let the dice be cast!\n";
  12. // create an ostream iterator
  13. ostream_iterator<int ,char> out_iter(cout, " ");
  14. // copy from vector to output
  15. copy(dice.begin(), dice.end(), out_iter);
  16. cout << endl;
  17. cout << "Implict use of reverse iterator.\n";
  18. copy(dice.rbegin(), dice.rend(), out_iter);
  19. cout << endl;
  20. cout << endl;
  21. cout << "Implicit use of reverse iterator.\n";
  22. vector<int >::reverse_iterator ri;
  23. for (ri = dice.rbegin(); ri != dice.rend(); ++ri)
  24. cout << *ri << ' ';
  25. cout << endl;
  26. }
  27. // insert
  28. void iteratorInsert(){
  29. string s1[4] = {"fine", "fish", "fashion", "fate"};
  30. string s2[2] = {"busy", "bats"};
  31. string s3[2] = {"silly", "singers"};
  32. vector<string> words(4);
  33. copy(s1, s1 + 4, words.begin());
  34. ostream_iterator<string, char> out(cout, " ");
  35. copy(words.begin(), words.end(), out);
  36. cout << endl;
  37. // construct anonymous back_insert_iterator object
  38. copy(s2, s2 + 2, back_insert_iterator<vector<string>>(words));
  39. copy(words.begin(), words.end(), out);
  40. cout << endl;
  41. // construct anonymous back_insert_iterator object
  42. copy(s3, s3 + 2, insert_iterator<vector<string>>(words, words.begin()));
  43. copy(words.begin(), words.end(), out);
  44. cout << endl;
  45. }
  46. int main() {
  47. useIterator();
  48. iteratorInsert();
  49. return 0;
  50. }

List相关操作

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <list>
  5. using namespace std;
  6. // List的相关操作
  7. void useList(){
  8. int stuff[5] = {1, 2, 4, 8, 6};
  9. list<int> two;
  10. two.insert(two.begin(), stuff, stuff + 5);
  11. int more[6] = {6, 4, 2, 4, 6, 5};
  12. list<int> three(two);
  13. three.insert(three.end(), more, more + 6);
  14. cout << "List two: ";
  15. ostream_iterator<int , char> out(cout, " ");
  16. copy(two.begin(), two.end(), out);
  17. cout << endl << "List three: ";
  18. copy(three.begin(), three.end(), out);
  19. three.remove(2);
  20. cout << endl << "List three minus 2s: ";
  21. copy(three.begin(), three.end(), out);
  22. three.splice(three.begin(), two);
  23. cout << endl << "List three after splice: ";
  24. three.unique();
  25. cout << endl << "List three after unique: ";
  26. copy(three.begin(), three.end(), out);
  27. three.sort();
  28. three.unique();
  29. cout << endl << "List three after sort & unique: ";
  30. copy(three.begin(), three.end(), out);
  31. two.sort();
  32. three.merge(two);
  33. cout << endl << "Sorted two merged into three: ";
  34. copy(three.begin(), three.end(), out);
  35. cout << endl;
  36. }
  37. int main() {
  38. useList();
  39. return 0;
  40. }

程序输出

  1. List two: 1 2 4 8 6
  2. List three: 1 2 4 8 6 6 4 2 4 6 5
  3. List three minus 2s: 1 4 8 6 6 4 4 6 5
  4. List three after splice:
  5. List three after unique: 1 2 4 8 6 1 4 8 6 4 6 5
  6. List three after sort & unique: 1 2 4 5 6 8
  7. Sorted two merged into three: 1 2 4 5 6 8

Set相关操作

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <set>
  5. using namespace std;
  6. // Set的相关操作
  7. void useSet(){
  8. const int N = 6;
  9. string s1[N] = {"buffon", "thinkers", "for", "heavy", "can", "for"};
  10. string s2[N] = {"metal", "any", "food", "elegant", "deliver", "for"};
  11. set<string> A (s1, s1 + N);
  12. set<string> B (s2, s2 + N);
  13. ostream_iterator<string, char> out(cout, "");
  14. cout << "Set A: ";
  15. copy(A.begin(), A.end(), out);
  16. cout << endl;
  17. cout << "Set B: ";
  18. copy(B.begin(), B.end(), out);
  19. cout << endl;
  20. cout << "Union of A and B: \n";
  21. set_union(A.begin(), A.end(), B.begin(), B.end(), out);
  22. cout << endl;
  23. cout << "Intersection of A and B:\n";
  24. set_intersection(A.begin(), A.end(), B.begin(), B.end(), out);
  25. cout << endl;
  26. cout << "Difference of A and B:\n";
  27. set_difference(A.begin(), A.end(), B.begin(), B.end(), out);
  28. cout << endl;
  29. set<string> C;
  30. cout << "Set C:\n";
  31. set_union(A.begin(), A.end(), B.begin(), B.end(), insert_iterator<set<string>>(C, C.begin()));
  32. copy(C.begin(), C.end(), out);
  33. cout << endl;
  34. string s3("grungy");
  35. C.insert(s3);
  36. cout << "Set C after insertion: \n";
  37. copy(C.begin(), C.end(), out);
  38. cout << endl;
  39. cout << "Showing a range:\n";
  40. copy(C.lower_bound("ghost"), C.upper_bound("spook"), out);
  41. cout << endl;
  42. }
  43. int main() {
  44. useSet();
  45. return 0;
  46. }

程序输出

  1. Set A: buffoncanforheavythinkers
  2. Set B: anydeliverelegantfoodformetal
  3. Union of A and B:
  4. anybuffoncandeliverelegantfoodforheavymetalthinkers
  5. Intersection of A and B:
  6. for
  7. Difference of A and B:
  8. buffoncanheavythinkers
  9. Set C:
  10. anybuffoncandeliverelegantfoodforheavymetalthinkers
  11. Set C after insertion:
  12. anybuffoncandeliverelegantfoodforgrungyheavymetalthinkers
  13. Showing a range:
  14. grungyheavymetal

容器-multimap相关操作

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <map>
  5. using namespace std;
  6. // multimap的相关操作
  7. typedef int KeyType;
  8. typedef pair<const KeyType, string> Pairs;
  9. typedef multimap<KeyType , string> MapCode;
  10. void useMultimap(){
  11. MapCode codes;
  12. codes.insert(Pairs(415, "San Francisco"));
  13. codes.insert(Pairs(510, "Oakland"));
  14. codes.insert(Pairs(718, "Brooklyn"));
  15. codes.insert(Pairs(718, "Staten Island"));
  16. codes.insert(Pairs(415, "San Rafael"));
  17. codes.insert(Pairs(510, "Berkeley"));
  18. cout << "Number if cities with area code 415: " << codes.count(415) << endl;
  19. cout << "Number if cities with area code 718: " << codes.count(718) << endl;
  20. cout << "Number if cities with area code 510: " << codes.count(510) << endl;
  21. cout << "Area Code City\n";
  22. MapCode::iterator it;
  23. for (it = codes.begin(); it != codes.end(); ++it){
  24. cout << " " << (*it).first << " " << (*it).second << endl;
  25. }
  26. pair<MapCode::iterator, MapCode::iterator> range = codes.equal_range(718);
  27. cout << "Cities with area code 718: \n";
  28. for (it = range.first; it != range.second; ++it)
  29. cout << (*it).second << endl;
  30. }
  31. int main() {
  32. useMultimap();
  33. return 0;
  34. }

程序输出

  1. Number if cities with area code 415: 2
  2. Number if cities with area code 718: 2
  3. Number if cities with area code 510: 2
  4. Area Code City
  5. 415 San Francisco
  6. 415 San Rafael
  7. 510 Oakland
  8. 510 Berkeley
  9. 718 Brooklyn
  10. 718 Staten Island
  11. Cities with area code 718:
  12. Brooklyn
  13. Staten Island

STL和String类

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <map>
  5. using namespace std;
  6. // STL和String类
  7. void stlString(){
  8. string letters;
  9. cout << "Enter the letter grouping (q to quit): ";
  10. while (cin >> letters && letters != "q"){
  11. cout << "Permutations of " << letters << endl;
  12. sort(letters.begin(), letters.end());
  13. cout << letters << endl;
  14. while (next_permutation(letters.begin(), letters.end()))
  15. cout << letters << endl;
  16. cout << "Enter next sequence (q to quit): ";
  17. }
  18. cout << "Done.\n";
  19. }
  20. int main() {
  21. stlString();
  22. return 0;
  23. }

程序输出

  1. Enter the letter grouping (q to quit): wed
  2. Permutations of wed
  3. dew
  4. dwe
  5. edw
  6. ewd
  7. wde
  8. wed
  9. Enter next sequence (q to quit): q
  10. Done.

函数和容器方法

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <map>
  5. using namespace std;
  6. // 函数和容器方法
  7. void View(int);
  8. void View(int v){
  9. cout << v << ' ';
  10. }
  11. const int LIMS = 10;
  12. void funList(){
  13. int ar[LIMS] = {4, 5, 4, 2, 2, 3, 4, 8, 1, 4};
  14. list<int> la(ar, ar + LIMS);
  15. list<int> lb(la);
  16. cout << "Original list contents: \n\t";
  17. for_each(la.begin(), la.end(), View);
  18. cout << endl;
  19. la.remove(4);
  20. cout << "After using the remove() method: \n";
  21. cout << "la: \t";
  22. for_each(la.begin(), la.end(), View);
  23. cout << endl;
  24. list<int>::iterator last;
  25. last = remove(lb.begin(), lb.end(), 4);
  26. cout << "After using the remove() function: \n";
  27. cout << "lb: \t";
  28. for_each(lb.begin(), lb.end(), View);
  29. cout << endl;
  30. lb.erase(last, lb.end());
  31. cout << "After using the erase() method: \n";
  32. cout << "lb: \t";
  33. for_each(lb.begin(), lb.end(), View);
  34. cout << endl;
  35. }
  36. int main() {
  37. funList();
  38. return 0;
  39. }

程序输出

  1. Original list contents:
  2. 4 5 4 2 2 3 4 8 1 4
  3. After using the remove() method:
  4. la: 5 2 2 3 8 1
  5. After using the remove() function:
  6. lb: 5 2 2 3 8 1 4 8 1 4
  7. After using the erase() method:
  8. lb: 5 2 2 3 8 1

使用STL

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <map>
  5. using namespace std;
  6. // 使用STL
  7. char toLower(char ch){ return tolower(ch); }
  8. string & ToLower(string & st);
  9. void display(const string & s);
  10. string & ToLower(string & st){
  11. transform(st.begin(), st.end(), st.begin(), toLower);
  12. return st;
  13. }
  14. void display(const string & s){
  15. cout << s << " ";
  16. }
  17. void useSTL(){
  18. vector<string> words;
  19. cout << "Enter words (enter q to quit): \n";
  20. string input;
  21. while (cin >> input && input != "q")
  22. words.push_back(input);
  23. cout << "You entered the following words:\n";
  24. for_each(words.begin(), words.end(), display);
  25. cout << endl;
  26. // place words in set, converting to lowercase
  27. set<string> wordset;
  28. transform(words.begin(), words.end(), insert_iterator<set<string>>(wordset, wordset.begin()), ToLower);
  29. cout << "\nAlphabetic list of words: \n";
  30. for_each(wordset.begin(), wordset.end(), display);
  31. cout << endl;
  32. // place word and frequency in map
  33. map<string, int> wordmap;
  34. set<string>::iterator si;
  35. for (si = wordset.begin(); si != wordset.end(); si++)
  36. wordmap[*si] = count(words.begin(), words.end(), *si);
  37. // display map contents
  38. cout << "\nWord frequency: \n";
  39. for (si = wordset.begin(); si != wordset.end(); si++)
  40. cout << *si << ": " << wordmap[*si] << endl;
  41. }
  42. int main() {
  43. useSTL();
  44. return 0;
  45. }

程序输出

  1. Enter words (enter q to quit):
  2. The dog saw the cat thought the cat fat the cat thought the cat perfact
  3. q
  4. You entered the following words:
  5. The dog saw the cat thought the cat fat the cat thought the cat perfact
  6. Alphabetic list of words:
  7. cat dog fat perfact saw the thought
  8. Word frequency:
  9. cat: 4
  10. dog: 1
  11. fat: 1
  12. perfact: 1
  13. saw: 1
  14. the: 5
  15. thought: 2

其他库的使用-Vector、valarray

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <valarray>
  5. using namespace std;
  6. // 其他STL库的使用
  7. void valvect(){
  8. vector<double > data;
  9. double temp;
  10. cout << "Enter numbers(<= 0 to quit):\n";
  11. while (cin >> temp && temp > 0)
  12. data.push_back(temp);
  13. sort(data.begin(), data.end());
  14. int size = data.size();
  15. valarray<double > numbers(size);
  16. int i;
  17. for (int i = 0; i < size; i++) {
  18. numbers[i] = data[i];
  19. }
  20. valarray<double > sq_rts(size);
  21. sq_rts = sqrt(numbers);
  22. valarray<double > result(size);
  23. result = numbers + 2.0 * sq_rts;
  24. cout.setf(ios_base::fixed);
  25. cout.precision(4);
  26. for (int i = 0; i < size; i++) {
  27. cout.width(8);
  28. cout << numbers[i] << ": ";
  29. cout.widen(8);
  30. cout << result[i] << endl;
  31. }
  32. cout << "Done!\n";
  33. }
  34. int main() {
  35. valvect();
  36. return 0;
  37. }

程序输出

  1. Enter numbers(<= 0 to quit):
  2. 5 21.2 6 8 2 10 14.4 0
  3. 2.0000: 4.8284
  4. 5.0000: 9.4721
  5. 6.0000: 10.8990
  6. 8.0000: 13.6569
  7. 10.0000: 16.3246
  8. 14.4000: 21.9895
  9. 21.2000: 30.4087
  10. Done!

slice的使用

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <valarray>
  5. using namespace std;
  6. // slice的使用
  7. const int SIZE = 12;
  8. typedef valarray<int> vint;
  9. void Show_s(const vint & v, int cols);
  10. void Show_s(const vint & v, int cols){
  11. int lim = v.size();
  12. for (int i = 0; i < lim; i++) {
  13. cout.width(3);
  14. cout << v[i];
  15. if (i % cols == cols - 1)
  16. cout << endl;
  17. else
  18. cout << ' ';
  19. }
  20. if (lim % cols != 0)
  21. cout << endl;
  22. }
  23. void useSlice(){
  24. vint valint(SIZE);
  25. for (int i = 0; i < SIZE; i++) {
  26. valint[i] = rand() % 10;
  27. }
  28. cout << "Original array: \n";
  29. Show_s(valint, 3);
  30. vint vcol(valint[slice(1, 4, 3)]);
  31. cout << "Second column: \n";
  32. Show_s(vcol, 1);
  33. valint[slice(2, 4, 3)] = 10;
  34. cout << "Set last column to 10 :\n";
  35. Show_s(valint, 3);
  36. cout << "Set first column to sum of next two:\n";
  37. valint[slice(0, 4, 3)] = vint(valint[slice(1, 4, 3)]) + vint(valint[slice(2, 4, 3)]);
  38. Show_s(valint, 3);
  39. }
  40. int main() {
  41. useSlice();
  42. return 0;
  43. }

程序输出

  1. Original array:
  2. 3 3 2
  3. 9 0 8
  4. 2 6 6
  5. 9 1 1
  6. Second column:
  7. 3
  8. 0
  9. 6
  10. 1
  11. Set last column to 10 :
  12. 3 3 10
  13. 9 0 10
  14. 2 6 10
  15. 9 1 10
  16. Set first column to sum of next two:
  17. 13 3 10
  18. 10 0 10
  19. 16 6 10
  20. 11 1 10

输出输入-write

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <valarray>
  5. using namespace std;
  6. void useWrite(){
  7. const char * state1 = "Florida";
  8. const char * state2 = "Kansas";
  9. const char * state3 = "Euphoria";
  10. int len = strlen(state2);
  11. cout << "Increasing loop index: \n";
  12. for (int i = 0; i < len; i++) {
  13. cout.write(state2, i);
  14. cout << endl;
  15. }
  16. cout << "Decreasing loop index: \n";
  17. for (int i = len; i > 0; i--)
  18. cout.write(state2, i) << endl;
  19. cout << "Exceeding string length:\n";
  20. cout.write(state2, len + 5) << endl;
  21. }
  22. int main() {
  23. useWrite();
  24. return 0;
  25. }

程序输出

  1. Increasing loop index:
  2. K
  3. Ka
  4. Kan
  5. Kans
  6. Kansa
  7. Decreasing loop index:
  8. Kansas
  9. Kansa
  10. Kans
  11. Kan
  12. Ka
  13. K
  14. Exceeding string length:
  15. Kansas Euph