c++ 自定义inserter

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <unordered_set>
using namespace std;

template<class C>
class asso_insert_iterator : 
	public std::iterator<std::output_iterator_tag,typename C::value_type>
{
protected: 
	C &c;
public:
	explicit asso_insert_iterator(C &c_):c(c_) {};
	auto& operator=(const typename C::value_type value) {
		c.insert(value);
		return *this;
	}
	auto& operator*() {
		return *this;
	}
	
	auto& operator++() {
		return *this;
	}
	auto& operator++(int) {
		return *this;
	}
};

template<class C>
inline auto asso_inserter(C &c) {
	return asso_insert_iterator<C>(c);
}

int main() {
	//cout  << "test\n";
	vector<int> coll {1,2,3,4,5};
	auto iter = istream_iterator<int>(cin);
	//copy(iter,istream_iterator<int>(),back_inserter(coll));
	//for(auto &n:coll) cout << n << "\t";
	
	
	unordered_set<int> coll2 {};
	asso_insert_iterator<decltype(coll2)> my_iter{coll2};
	*my_iter = 1;
	copy(coll.begin(),coll.end(),asso_inserter(coll2));
	for(auto &n:coll2) cout << n;
	cout << endl;
	return 0;
}

 

上一篇:C#.NET 各种连接字符串


下一篇:尚硅谷JavaSE入门笔记 - P516 ~ P561