本文介绍了如何使用std :: copy读取任意数量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图代码与此相反的行动:
I'm trying to code opposite action to this:
std::ostream outs; // properly initialized of course
std::set<int> my_set; // ditto
outs << my_set.size();
std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) );
应该是这样:
std::istream ins;
std::set<int>::size_type size;
ins >> size;
std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) );
但是我遇到了'end'迭代器 - 输入拦截器不能使用std: :提前,我不能使用同一来源的两个流...
But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source...
有没有任何优雅的方式如何解决这个?当然我可以使用for循环,但也许有更好的东西:)
Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)
推荐答案
你可以从istream_iterator派生&
虽然使用是另一个选项,虽然我会直接生成集合,而不是使用中间向量。
You could derive from the istream_iterator<T>.
Though using Daemin generator method is another option, though I would generate directly into the set rather than use an intermediate vector.
#include <set>
#include <iterator>
#include <algorithm>
#include <iostream>
template<typename T>
struct CountIter: public std::istream_iterator<T>
{
CountIter(size_t c)
:std::istream_iterator<T>()
,count(c)
{}
CountIter(std::istream& str)
:std::istream_iterator<T>(str)
,count(0)
{}
bool operator!=(CountIter const& rhs) const
{
return (count != rhs.count) && (dynamic_cast<std::istream_iterator<T> const&>(*this) != rhs);
}
T operator*()
{
++count;
return std::istream_iterator<T>::operator*();
}
private:
size_t count;
};
int main()
{
std::set<int> x;
//std::copy(std::istream_iterator<int>(std::cin),std::istream_iterator<int>(),std::inserter(x,x.end()));
std::copy(
CountIter<int>(std::cin),
CountIter<int>(5),
std::inserter(x,x.end())
);
}
这篇关于如何使用std :: copy读取任意数量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!