/*
输入输出,正反迭代器的使用;
程序输出:
Let the dice be cast!
6 7 4 5 2 6 7 10 16 5
Implicit use of reverse iterator.
5 16 10 7 6 2 5 4 7 6
Explicit use of reverse iterator.
5 16 10 7 6 2 5 4 7 6
*/
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
int casts[10] = {6, 7, 4, 5, 2, 6, 7, 10, 16, 5};
vector<int> dice(10);
//copy from array to vector
copy(casts, casts + 10, dice.begin());
cout << "Let the dice be cast! \n";
//create an ostream iterator
ostream_iterator<int, char> out_iter (cout, " ");
//copy from vector to output
copy(dice.begin(), dice.end(), out_iter);
cout << endl;
cout << "Implicit use of reverse iterator. \n";
copy(dice.rbegin(), dice.rend(), out_iter);
cout <<endl;
cout << "Explicit use of reverse iterator. \n";
vector<int>:: reverse_iterator riter;
for (riter = dice.rbegin(); riter != dice.rend(); ++riter)
{
cout << *riter << ' ';
}
cout << endl;
getchar();
return 0;
}
注意:
一、copy()不仅仅可以将信息从一个容器复制到另一个容器中,还可以将信息从容器复制到输出流,从输入流复制到容器中。还可以使用copy()将信息插入到另一个容器中。
二、rbegin()和end()返回相同的值(超尾),但类型不同(reverse_iterator和iterator)。rend()和begin()同理。
/*
联合容器set事例,及用copy()输出到显示器的方法。
知识点:
联合容器,multiset容器类似于set,但前者可能有多个值得关键字相同。
但后者关键字唯一,其值就是关键字。因此,其不能指定元素的插入位置,
其保存的数据时经过排序的。
程序输出:
Set A:buffon can for heavy thinkers
Set B:any deliver elegant food for metal
Union of A and B:
any buffon can deliver elegant food for heavy metal thinkers
Intersection of A and B:
for
Difference of A and B:
buffon can heavy thinkers
Set C:
any buffon can deliver elegant food for heavy metal thinkers
Set C affter insertion:
any buffon can deliver elegant food for grungy heavy metal thinkers
showing a range:
grungy heavy metal
*/
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
const int N = 6;
string s1[N] = {"buffon", "thinkers", "for", "heavy", "can", "for"};
string s2[N] = {"metal", "any", "food", "elegant", "deliver", "for"};
set<string> A(s1, s1 + N);
set<string> B(s2, s2 + N);
ostream_iterator<string, char> out(cout, " ");
cout << "Set A:";
copy(A.begin(), A.end(), out);
cout << endl;
cout << "Set B:";
copy(B.begin(), B.end(), out);
cout << endl;
cout << "Union of A and B: \n";
set_union(A.begin(), A.end(), B.begin(), B.end(), out);
cout << endl;
cout << "Intersection of A and B: \n";
set_intersection(A.begin(), A.end(), B.begin(), B.end(), out);
cout << endl;
cout << "Difference of A and B: \n";
set_difference(A.begin(), A.end(), B.begin(), B.end(), out);
cout << endl;
set<string> C;
cout << "Set C: \n";
set_union(A.begin(), A.end(), B.begin(), B.end(), insert_iterator<set<string>> (C, C.begin()));
copy(C.begin(), C.end(), out);
cout << endl;
string s3("grungy");
C.insert(s3);
cout << "Set C affter insertion: \n";
copy(C.begin(), C.end(), out);
cout << endl;
cout << "showing a range: \n";
copy(C.lower_bound("ghost"), C.upper_bound("spook"), out);
cout << endl;
getchar();
return 0;
}