c++ vector和数组的相互复制,vector的逆向迭代器

#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方法

这么高级的iteratorcopy,真的有人会想起去用他们吗

#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值