0

Again reading C++ Primer 5th Edition: I am practicing stream iterators. Here is an example I can't really understand:

In the book there's an example like this:

std::istream_iterator<int> in_iter(std::cin), eof;
std::vector<int> vec;
while (in_iter != eof) vec.push_back(*in_iter++);
std::sort(vec.begin(), vec.end());
std::copy(vec.cbegin(), vec.cend(),
          std::ostream_iterator<int>(std::cout, " "));

This program is to read a sequence of integers from the input stream using npput stream iterator into a vector, sort them then copy them into output stream using an output stream iterator.

  • I wan't to change a bit the code: The fact that a vector is a container that can be constructed from a range of elements denoted by two iterators thus I've done this:

    std::vector<int> vi(std::istream_iterator<int>(std::cin), std::istream_iterator<int>()); // error here?!
    
    //std::copy(iit, off, std::back_inserter(vi));
    std::sort(vi.begin(), vi.end()); // error?
    std::copy(vi.cbegin(), vi.cend(),  std::ostream_iterator<int>(std::cout, ", ")); // error?
    

However the initialization of vi flags an error: Severity Code Description Project File Line Suppression State Error (active) expression must have class type.

However If I change it to uniform-initialize the Off-End iterator in vi constructor it works just fine!:

    std::vector<int> vi(std::istream_iterator<int>(cin), std::istream_iterator<int>{});  // works fine!?

** In fact this:

    std::vector<int> vi(std::istream_iterator<int>(std::cin), std::istream_iterator<int>()); // error here?!

Doesn't flag an error but the copy algorithm does. Because I think there's something wrong inside the vector? After all can you explain me what does this vector have?

rafix07
  • 20,001
  • 3
  • 20
  • 33
Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • @rafix07 Why you've flagged it as a duplicate? It contains some part that is not found the link you marked as duplicate: The program runs fine if I uniform-initialize to the vector: `std::vector vi(std::istream_iterator(cin), std::istream_iterator{});`. – Itachi Uchiwa Sep 24 '19 at 12:56
  • because uniform initialization was introduced to avoid problems with *most vexing parse* (read more [here](https://softwareengineering.stackexchange.com/questions/133688/is-c11-uniform-initialization-a-replacement-for-the-old-style-syntax)). It is easy to pair both things up. – rafix07 Sep 24 '19 at 13:10
  • @rafix07: I got it now thanx. So I've tried to use `typeid` on that initialization: `cout << typeid(vector()).name() << endl;` The result I get: `class std::vector > __cdecl(void)` which is a function while `cout << typeid(vector{}).name() << endl; // class std::vector >`. – Itachi Uchiwa Sep 24 '19 at 13:41

0 Answers0