mardi 24 septembre 2019

How Can I initialize a vector of integers directly from a range of elements denoted by input-stream-iterators?

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?

Aucun commentaire:

Enregistrer un commentaire