c++ 自定义inserter

2021/9/18 20:35:04

本文主要是介绍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++ 自定义inserter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程