Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The following codes can be executed correctly,and print 1 2 3

std::allocator<int> alloc;
auto begin = alloc.allocate(3);
std::vector<int> ivec = { 1,2,3 };
std::uninitialized_copy(ivec.begin(), ivec.end(), begin);
for (auto q = begin; q != begin + 3; ++q)
cout << *q << " ";
alloc.deallocate(begin, 3);

But,the following codes can not be executed, when the program is running,there is an error : cannot seek vector iterator after end

std::vector<int> ivec_1 = { 1,2,3 };
std::vector<int> ivec_2;
std::uninitialized_copy(ivec_1.begin(), ivec_1.end(), ivec_2.begin());

My question is: First of all,I know the error is because the iterator exceeds after-end iterator. Generics algorithms which require three iterators always assume that destination sequences at least have the same length as source sequences.In other word,destination sequences must be able to contain all elements from source sequences.But, "The same length" here refer to what ?

1. The quantity of actual elements between source sequences and destination sequences is the same ?
2. The quantity of memories(not actual element is required) that source sequences and destination sequences have is the same ?

If it requires the same quantity of actual elements. Why doesn't the first code report errors ? I use std::allocator to allocate 3 memories. And these memories are uninitialized, there are no elements constructed in these memories. But std::uninitialized_copy succeed in copying the elements from source sequences to destination sequences.

If it requires the same quantity of memories(not actual element is required). Then why the second code report an error ? At first, ivec_2 is empty. And I call reserve(3) to allocate 3 memories previously for it. I even call capacity() to make sure that it actually allocates 3 memories.And there are no actual elements in ivec_2.But this time std::uninitialized_copy doesn't work and report an error.

What I have tried:

When I call resize(3) for ivec_2. std::uninitialized_copy can work correctly.
This question has puzzled me a few days,please help,thank you so much!
Updated 22-May-22 19:00pm

1 solution

reserve() does not change the size of the vector. You need to use resize(3)
Share this answer
CPallini 23-May-22 2:05am    
Member 15645256 23-May-22 5:54am    
Thank you.Yes,I know that reserve() does not change the size of the vector. And the size() just shows how many elements the vector has. But reserve() can provide extra memories with vector. And these memories are currently not used to store any elements. Why can't I use std::uninitialized_copy to copy elements to these memories.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900