简单的vector类的使用
#include<iostream> #include<string> #include<vector> using namespace std; const int NUM = 5; int main() { vector<int> ratings(NUM); vector<string> titles(NUM); cout<<"You will do exactly as told. You will enter\n" <<NUM<<" book titles and your ratings (0-10).\n"; int i; for(i=0;i<NUM;i++) { cout<<"Enter title #"<<i+1<<": "; getline(cin,titles[i]); cout<<"Enter your rating (0-10): "; cin>>ratings[i]; cin.get(); } cout<<"Thank you.You entered te following:\n" <<"Ratings\tBook\n"; for(i=0;i<NUM;i++) cout<<ratings[i]<<"\t"<<titles[i]<<endl; return 0; }
ratings.begin();//指向表示容器第一个元素的迭代器 ratings.end();//指向表示超过容器尾的迭代器 ratings.push_back(5);//在末尾添加元素 cout<<ratings.size();//容器中的数目 ratings.erase(ratings.begin(),ratings.begin()+2);//定区间删除 intsert为定点插入 它接受三个迭代器参数,第一个指定了新元素的插入位置,第二个和第三个迭代器参数定义了被插入区间,该区间通常是另一个容器对象的一部分。 vector<int> old_v; vector<int>new_v; …… old_v.insert(old_v.begin(),new_v.begin()+1,new_v.end()); 而且,这样拥有超尾元素是非常方便的,这使得在矢量尾部附加元素非常简单 old_v.insert(old_v.end(),new_v.begin()+1,new_v.end());基本操作的使用例子
#include<iostream> #include<string> #include<vector> using namespace std; struct Review { std::string title; int rating; }; bool FillReview(Review & rr); void ShowReview(const Review & rr); int main() { 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\tbook\n"; for(int i=0;i<num;i++) ShowReview(books[i]); cout<<"Reprising:\n" <<"Rating\tbook\n"; vector<Review>::iterator pr;//指针 for(pr=books.begin();pr!=books.end();pr++) ShowReview(*pr); vector<Review> oldlist(books);//被用来拷贝结构体 if(num>3) { //romove 2 items books.erase(books.begin()+1,books.begin()+3); cout<<"After insertion:\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) { cout<<"Enter book title (quit to quit):"; getline(cin,rr.title); if(rr.title=="quit") return false; cout<<"Enter book rating: "; cin>>rr.rating; if(!cin) return false; //get rid of rest of input line while(cin.get()!='\n') continue; return true; } void ShowReview(const Review & rr) { cout<<rr.rating<<"\t"<<rr.title<<endl; }
3个代表性的STL函数:for_each()、random_shuffle()和sort().
vector<Review>::iterator pr; for(pr==books.begin();pr!=books.end();pr++) ShowReview(*pr); <span style="font-size:18px;color:#3333FF;">可以替换为</span> for_each(books.begin(),books,end(),ShowReview);
Random_shuffle()函数,