(1)back_inserter,创建一个使用push_back()的迭代器.
(2)front_inserter,创建一个使用push_front()的迭代器.
(3)inserter创建一个使用insert的迭代器.此函数接受第二个参数,一个指向给定容器的迭代器.元素将被插入到给定迭代器所表示的元素之前.
注意,容器必须支持相应操作才能够用相应的插入迭代器;
.
vector<int> vec{ 1, 2,2,3, 3, 4, 5, 6, 7, 8, 9 };
list<int> lst;
unique_copy(vec.cbegin(), vec.cend(), inserter(lst,lst.begin()));
vector<int> vec{ 1, 2,2,3, 3, 4, 5, 6, 7, 8, 9 },vec1,vec2;
list<int>lst;
copy(vec.cbegin(), vec.cend(),back_inserter(vec1));
print(vec1);
copy(vec.cbegin(), vec.cend(), inserter(vec2, vec2.begin()));
print(vec2);
copy(vec.cbegin(), vec.cend(), front_inserter(lst));
print(lst);
======================================================================================
istream_iterator<string> in(cin);
istream_iterator<string> eof//尾后迭代器
ostream_iterator<string> out(cout);
ostream_iterator<string> out(os,d)//d是一个字符串,每次输出都会有d;
vector<string> vec(in,eof)//直接通过迭代器来构造vec.不需要编写循环
ifstream in("Text.txt");//in绑定到Text;
istream_iterator<string> str_in(in);//迭代器str_in 绑定到流ifstream上
istream_iterator<string> eof;
S ves;
copy(str_in, eof, back_inserter(ves));
copy(ves.cbegin(), ves.cend(),ostream_iterator<string>(cout, "\n"));
return 0;
istream_iterator<int> in(cin);
istream_iterator<int> eof;
vector<int> vec;
copy(in, eof, back_inserter(vec));
sort(vec.begin(), vec.end());
copy(vec.cbegin(),vec.cend(),ostream_iterator<int> (cout, " "));
return 0;
int main()
{
istream_iterator<Sales_item> in(cin),eof;//输入数据
vector<Sales_item> vec(in, eof);
sort(vec.begin(), vec.end(), [](const Sales_item&s1,
const Sales_item&s2){return s1.isbn() < s2.isbn(); });//排序
Sales_item sum;
for (auto start = vec.begin(), newend = vec.end(); start != vec.end(); start = newend)
{
newend = find_if(start, vec.end(),
[start](const Sales_item & it){ return it.isbn()!=start->isbn();});//获取第一个不等的
cout<<start->isbn()<<" : "<< accumulate(start, newend,Sales_item())<<endl;
}
return 0;
}
void func(const string& in_name, const string& odd_name,const string& even_name)
{
ifstream is_file(in_name);
ofstream os1(odd_name), os2(even_name);
istream_iterator<int> is(is_file), eof;
ostream_iterator<int> out1(os1, " "), out2(os2, "\n");
vector<int> vec;
copy(is, eof, back_inserter(vec));
for (auto element : vec)
(element % 2 ? out1 : out2) = element;
//另外一种写入方法
//for_each(is, eof, [&out1, &out2](const int i)
//{ ((i % 2) ? out1 : out2) = i; });
}
======================================================================================
sort(vec.rbegin(),vec.rend());//反向排序
vector<int>vec{ 1, 2,0, 3, 4, 5, 6, 7,0, 8, 9 };
auto it = find(vec.rbegin(), vec.rend(), 0);
cout << *it << endl;
vector<int>vec{ 1, 2,0, 3, 4, 5, 6, 7,0, 8, 9 };
list<int> lst(vec.rbegin()+3,vec.rend()-3);