I\'m trying to code opposite action to this:
std::ostream outs; // properly initialized of course
std::set my_set; // ditto
outs << my_set.
Errr... copy_n() algorithm?
Looking into this a bit I don't think reading directly into a set will work, as you need to call insert on it to actually add the elements (I could be mistaken, it is rather early in the morning here). Though looking at the STL documentation in VS2005 briefly I think something using the generate_n function should work, for instance:
std::istream ins;
std::set<int> my_set;
std::vector<int> my_vec;
struct read_functor
{
read_functor(std::istream& stream) :
m_stream(stream)
{
}
int operator()
{
int temp;
m_stream >> temp;
return temp;
}
private:
std::istream& m_stream;
};
std::set<int>::size_type size;
ins >> size;
my_vec.reserve(size);
std::generate_n(my_vec.begin(), size, read_functor(ins));
my_set.insert(my_vec.begin(), my_vec.end());
Hopefully that's either solved your problem, or convinced you that the loop isn't that bad in the grand scheme of things.
Yes sdg but when I want to use another data structures in that file / stream? I should probably explicitly write here, I want to store another stuff after this set, this is the reason why I'm storing the size as well.
Or you could do this:
my_set.insert(std::istream_iterator<int>(ins), std::istream_iterator<int>());
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())
);
}
Use:
std::copy( std::istream_iterator<int>(ins),
std::istream_iterator<int>(),
std::inserter(my_set, my_set.end())
);
Note the empty parameter:
std::istream_iterator<int>();