/*
*STL提供的一些基本的方法:
*1)size()返回容器中元素数目;
*2)swap()交换两个容器的内容;
*3)begin()返回一个指向容器中的第一个元素中的迭代器;
*4)end()返回一个表示超过容器尾的迭代器;
*5)push_back()是一个方便的方法,它将元素添加到矢量
*6)erase()方法删除矢量中给定的区间元素;
*7)inser()方法的功能与erase()相反;
*下面介绍一下这几个方法:
*/
#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);
int num = books.size();
if (num > 0) {
cout << "Thank you. You entered the following: \n"
<< "Rating\t tBook\n";
for (int i = 0; i < num; i++)
ShowReview(books[i]);
cout << "Reprising: \n" << "Rating\t Book\n";
// 定义一个迭代器,用迭代器来遍历books数组
vector<Review>::iterator pr;
for (pr = books.begin(); pr != books.end(); pr++)
ShowReview(*pr);
//拷贝构造函数的使用
vector<Review> oldlist(books);
if (num > 3) {
// erase()删除适量中给定区间的元素,他接受两个参数,这些参数定义了要删除的区间;
books.erase(books.begin() + 1, books.begin() + 3);
cout << "After erasure:\n";
for (pr = books.begin(); pr != books.end(); pr++)
ShowReview(*pr);
// insert()与erase()相反,他接受三个参数,第一个参数制定了新元素插入位置,第二个和第三个定义了被插入区间;
books.insert(books.begin(), oldlist.begin() + 1,
oldlist.begin() + 2);
cout << "After insertiong: \n";
for (pr = books.begin(); pr != books.end(); pr++)
ShowReview(*pr);
}
books.swap(oldlist);
cout << "Swapping oldlist with books: \n";
for (pr = books.begin(); pr != books.end(); pr++)
ShowReview(*pr);
} else
cout << "Nothing entered, nothing gained. \n";
return 0;
}
bool FillReview(Review & rr) {
std::cout << "Enter book title (quit to quit):";
std::getline(std::cin, rr.title);
if (rr.title == "quit")
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;
}
Primer plus C++ 第十六章 标准模板库_vector模板类方法
于 2012-12-21 20:23:40 首次发布