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;
ivec_2.reserve(3);
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!