// 程序清单_16.6_vect2.cpp -- methods and iterators
// 这次的注释是个人加上去的
/*******************************************************************************
让我们先看一下运行结果吧:
Enter book title(quit to quit):The Cat who Knew Vectors
Enter book rating:5
Enter book title(quit to quit):Candid Canines
Enter book rating:7
Enter book title(quit to quit):Warriors of Work
Enter book rating:4
Enter book title(quit to quit):Quantum Manners
Enter book rating:8
Enter book title(quit to quit):quit
Thank you. You entered the follow:
Rating Book
5 The Cat who Knew Vectors
7 Candid Canines
4 Warriors of Work
8 Quantum Manners
5 The Cat who Knew Vectors
7 Candid Canines
4 Warriors of Work
8 Quantum Manners
After erasure:
5 The Cat who Knew Vectors
8 Quantum Manners
After insertion:
7 Candid Canines
5 The Cat who Knew Vectors
8 Quantum Manners
Swapping oldlist with books:
5 The Cat who Knew Vectors
7 Candid Canines
4 Warriors of Work
8 Quantum Manners
*******************************************************************************/
#include <iostream>
#include <string>
#include <vector>
struct Review
{
std::string title;
int rating;
};
bool FillReview(Review & rr);
void ShowReview(const Review & rr);
int main()
{
using std::cout;
using std::vector;
vector<Review> books; // 定义容器的方法
Review temp;
while(FillReview(temp))
books.push_back(temp); // 容器将数据放到容器后的函数.push_back()
int num = books.size(); // 可用.size()测出容器的个数
if(num > 0)
{
cout << "Thank you. You entered the follow:\n"
<< "Rating\tBook\n";
for (int i = 0; i < num; i++)
{
ShowReview(books[i]);
}
vector<Review>::iterator pr; // 定义迭代器,可将其看为容器的指针
for (pr = books.begin(); pr != books.end(); pr++) // 迭代器可读取容器中的内容
{
ShowReview(*pr);
}
vector<Review> oldlist(books); // copy constructor used
if (num > 3)
{
// remove 2 items
books.erase(books.begin() + 1, books.begin() + 3);
cout << "After erasure:\n";
for (pr = books.begin(); pr != books.end(); pr++)// 开始与结束的位置
{
ShowReview(*pr);
}
// insert 1 item
books.insert(books.begin(), oldlist.begin() + 1, oldlist.begin() + 2);// 将后面空间的内容插入到开始的参数的位置
cout << "After insertion:\n";
for (pr = books.begin(); pr != books.end(); pr++)
{
ShowReview(*pr);
}
}
books.swap(oldlist); // 将容器 oldlist 与 books 整个交换,可以理解成两个容器换了名字,不过值的地址也是有改变的。
cout << "Swapping oldlist with books:\n";
for (pr = books.begin(); pr != books.end(); pr++)
{
ShowReview(*pr);
}
}
else
cout << "Nothing entered, nothing gained.\n";
std::cin.get();
return 0;
}
bool FillReview(Review & rr)
{
std::cout << "Enter book title(quit to quit):";
std::getline(std::cin, rr.title);
if (rr.title == "quit") // 使用这个函数可以方便地退出程序,system call时。返回false
{
return false;
}
std::cout << "Enter book rating:";
std::cin >> rr.rating;
if (!std::cin)
return false;
std::cin.get();
return true;
}
void ShowReview (const Review &rr)
{
std::cout << rr.rating << "\t" << rr.title << std::endl;
}
(2011.07.11)程序清单_16.6_vect2.cpp -- methods and iterators
最新推荐文章于 2022-04-13 22:45:49 发布