vec_init.cpp
上传用户:qdkongtiao
上传日期:2022-06-29
资源大小:356k
文件大小:2k
源码类别:

书籍源码

开发平台:

Visual C++

  1. /*
  2.  * This file contains code from "C++ Primer, Fourth Edition", by Stanley B.
  3.  * Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the
  4.  * copyright and warranty notices given in that book:
  5.  * 
  6.  * "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo."
  7.  * 
  8.  * 
  9.  * "The authors and publisher have taken care in the preparation of this book,
  10.  * but make no expressed or implied warranty of any kind and assume no
  11.  * responsibility for errors or omissions. No liability is assumed for
  12.  * incidental or consequential damages in connection with or arising out of the
  13.  * use of the information or programs contained herein."
  14.  * 
  15.  * Permission is granted for this code to be used for educational purposes in
  16.  * association with the book, given proper citation if and when posted or
  17.  * reproduced.Any commercial use of this code requires the explicit written
  18.  * permission of the publisher, Addison-Wesley Professional, a division of
  19.  * Pearson Education, Inc. Send your request for permission, stating clearly
  20.  * what code you would like to use, and in what specific way, to the following
  21.  * address: 
  22.  * 
  23.  *  Pearson Education, Inc.
  24.  *  Rights and Contracts Department
  25.  *  75 Arlington Street, Suite 300
  26.  *  Boston, MA 02216
  27.  *  Fax: (617) 848-7047
  28. */ 
  29. #include <vector>
  30. #include <iostream>
  31. using std::vector;
  32. using std::cout;
  33. using std::endl;
  34. int main()
  35. {
  36.     
  37.     vector<int> ivec;                // empty vector
  38.     int cnt = 10;
  39.     // add elements 10...1 to ivec
  40.     while (cnt > 0)
  41.         ivec.push_back(cnt--);        // int postfix decrement
  42.     vector<int>::iterator iter = ivec.begin();
  43.     // prints 10 9 8 ... 1 
  44.     while (iter != ivec.end())
  45.         cout << *iter++ << endl; // iterator postfix increment
  46. // Alternative loop using comma operator in the for expression
  47. {
  48.     int cnt = ivec.size();
  49.     // add elements from size...1 to ivec
  50.     for(vector<int>::size_type ix = 0; 
  51.                     ix != ivec.size(); ++ix, --cnt)   
  52.         ivec[ix] = cnt;
  53.     vector<int>::iterator iter = ivec.begin();
  54.     // prints 10 9 8 ... 1 
  55.     while (iter != ivec.end())
  56.         cout << *iter++ << endl; // iterator postfix increment
  57. }
  58.     return 0;
  59. }