#include<iostream>
#include<iterator>
#include<vector>
int main()
{
using namespace std;
int casts[10] = { 6,7,2,9,4,11,8,7,10,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 ri;
for (ri = dice.rbegin(); ri != dice.rend(); ++ri)
{
cout << *ri << " ";
}
cout << endl;
return 0;
}
结果
let the dice be cast!
6 7 2 9 4 11 8 7 10 5
implicit use of reverse iterator.
5 10 7 8 11 4 9 2 7 6
explicit use of reverse iterator.
5 10 7 8 11 4 9 2 7 6
运行迭代器的copy
方法
这么高级的iterator
和copy
,真的有人会想起去用他们吗
#include<iostream>
#include<string>
#include<iterator>
#include<vector>
#include<algorithm>
void output(const std::string& s) { std::cout << s << " "; }
int main()
{
using namespace std;
string s1[4] = { "fine","fish","fashion","fate" };
string s2[2] = { "busy","bats" };
string s3[2] = { "silly","singers" };
vector<string> words(4);
copy(s1, s1 + 4, words.begin());
for_each(words.begin(), words.end(), output);
cout << endl;
// constructor anonymous back_insert_iterator object
copy(s2, s2 + 2, back_insert_iterator<vector<string>>(words));
for_each(words.begin(), words.end(), output);
cout << endl;
// construct anonymous insert_iterator object
copy(s3, s3 + 2, insert_iterator<vector<string>>(words, words.begin()));
for_each(words.begin(), words.end(), output);
cout << endl;
return 0;
}
结果
fine fish fashion fate
fine fish fashion fate busy bats
silly singers fine fish fashion fate busy bats