How to read arbitrary number of values using std::copy?

后端 未结 8 697
情深已故
情深已故 2021-01-05 02:24

I\'m trying to code opposite action to this:

std::ostream outs; // properly initialized of course
std::set my_set; // ditto

outs << my_set.         


        
相关标签:
8条回答
  • 2021-01-05 02:53

    (Edited: I should have read the question closer...)

    While somewhat suspect, you can get approximately the right behavior by having an entry in the file that will "fail" the first loop, then clear the fail bit on the stream and start reading more.

    Data, without an explicit size, but like this

    1 1 2 3 5 8 Fibb
    

    Fed to the code below seems to do what I meant, at least on VS2005 with STLPort.

    typedef std::istream_iterator < int, char, std::char_traits ,ptrdiff_t> is_iter;
    std::copy( is_iter(cin), is_iter(), inserter(my_set,my_set.end()));
    cin.clear();
    std::cin >> instr;
    
    0 讨论(0)
  • 2021-01-05 03:03

    How about using an alternate iterator to do the traversal and then use a function object (or lambda) to fill in the container?

    istream ins;
    set<int>::size_type size;
    set<int> new_set;
    ins >> size;
    ostream_iterator<int> ins_iter(ins);
    
    for_each(counting_iterator<int>(0), counting_iterator<int>(size),
      [&new_set, &ins_iter](int n) { new_set.insert(*ins_iter++); }
    );
    

    Of course this assumes you have a C++0x compliant compiler.

    BTW, 'counting_iterator<>' is part of Boost.Iterator.

    0 讨论(0)
提交回复
热议问题