-1
vector<int> data(istream_iterator<int>(cin),
istream_iterator<int>{});   cout<<"Size is : " << data.size() << endl; //compile success

vector<int> data1(istream_iterator<int>(cin),
std::allocator<int>{});   cout<<"Size is : " << data1.size() << endl; //compile failure

 error: no matching function for call to ‘std::vector<int>::vector(std::istream_iterator<int>, std::allocator<int>)’    vector<int> data1(istream_iterator<int>(cin), std::allocator<int>{});

Why is the first statement fine but second? Doesn't the vector take int type allocator in this case? I am experimenting with allocators.

18
  • 2
    Because the second one doesn't make sense? What does it mean to create a vector from a beginning iterator and an allocator? Commented Oct 28, 2020 at 13:55
  • 1
    istream_iterator<int>{} represents the matching end iterator for istream_iterator<int>(cin) as begin iterator. (For input iterators, it's valid to use a default constructed (aka. singular iterator) as end iterator - as I recently learnt.) Commented Oct 28, 2020 at 13:56
  • 1
    @InQusitive istream_iterator<int>{} is not an allocator. It's a sentinel iterator (end iterator for a stream) Commented Oct 28, 2020 at 13:57
  • 1
    with some practice we could do this even more synced :P Commented Oct 28, 2020 at 14:01
  • 1
    If you remove the end iterator from the first statement, it tries to use one of the numerous other (but non-matching) constructors. You need the constructor for a range given by begin and end iterator and none of them is provided with a default argument (as this wouldn't make much sense). So, you always have to give both. Commented Oct 28, 2020 at 15:04

1 Answer 1

5

Why is the first statement fine

Because vector has a constructor that accepts two iterators (and an allocator with default argument). Those iterators represent beginning and end of an input range.

but second [is not]?

Because vector doesn't have a constructor that accepts a single iterator and an allocator.

Sign up to request clarification or add additional context in comments.

2 Comments

[Not referring my code] Why doesn't vector have single iterator with allocator but is having two iterator with allocator?
@InQusitive Because a single iterator cannot represent a range. How could the constructor know how many elements to read from the iterator?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.