1. 程式人生 > >C++ : 插入迭代器,流迭代器,反向迭代器,移動迭代器的應用例項

C++ : 插入迭代器,流迭代器,反向迭代器,移動迭代器的應用例項

插入迭代器:back_inserter、front_inserter、inserter

流迭代器:istream_iterator(讀取輸入流)、ostream_iterator(讀取輸出流)

反向迭代器:rbegin()、rend()、crbegin()、crend()

 

應用例項:

#include<iostream>
#include<algorithm>
#include<list>
#include<numeric>
#include<vector>
#include<string>
#include<iterator>
//#include<functional>

using namespace std;

void printList(const list<string> &ls, list<string>::iterator &it)
{
	while (it != ls.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;
}

// 正向列印
void printvec(const vector<int>&vec)
{
	for_each(vec.begin(), vec.end(), [](const int&i) {cout << i << " "; });
	cout << endl;
}

// 反向列印
void rprintvec(const vector<int>&vec)
{
	for_each(vec.rbegin(), vec.rend(), [](const int&i) {cout << i << " "; });                    // 反向列印
	//for_each(vec.rend().base(), vec.rbegin().base(), [](const int&i) {cout << i << " "; });    // 正向列印
	cout << endl;
}

int main()
{
	istream_iterator<int> cin_int(cin);
	istream_iterator<int> cin_eof; //尾後迭代器

	//cout << "sum = " << accumulate(cin_int, cin_eof, 0) << endl;
	vector<int> vec(cin_int, cin_eof);
	
	//vector<int> vec = { 1,1,1,2,2,3,4,5 };
	printvec(vec);

	vector<int>::iterator it = vec.begin();
	//inserter(vec,it) = 99;
	back_inserter(vec) = 98;
	printvec(vec);

	ostream_iterator<int> cout_int(cout, " ");
	copy(vec.begin(), vec.end(), cout_int);
	cout << endl;

	rprintvec(vec);

	/*
	int b = 10;
	auto mysum = [&b](int a)mutable -> int
	{
		if (a < 0)
		{
			return -1;
		}
		else
		{
			return a + b;
		}
		
	};

	cout << mysum(2) << endl;
	
	list<string> ls = {"hello", "world", "ni", "hao"};
	list<string>::iterator it;
	int num = count(ls.cbegin(), ls.cend(),"ni");
	cout << num<< endl;
	string s = "";
	string strsum = accumulate(ls.cbegin(), ls.cend(), s);
	cout << "strsum = " << strsum << endl;
	it = ls.begin();
	printList(ls, it);

	vector<int> vec = {1,1,1,2,2,3,4,5};
	vector<int>::iterator it3 = vec.begin();
	auto it2 = back_inserter(vec);
	*it2 = 100;
	int sum = accumulate(vec.cbegin(), vec.cend(), 0);
    cout << "sum = " << sum << endl;
	//printvec(vec, vec.begin());
	//
	it3 = vec.begin();
	printvec(vec, it3);
	
	auto end_unique = unique(vec.begin(), vec.end());

	it3 = vec.begin();
	printvec(vec, it3);
	printvec(vec, end_unique);
	end_unique = unique(vec.begin(), vec.end());
	//vec.erase(end_unique, vec.end());
	//vec.erase(end_unique);
	it3 = vec.begin();
	printvec(vec, it3);
	*/

	system("pause");
	return 0;
}