The problem, as has been thoroughly pointed out, is that the vector reallocates its storage while the modifications are being done. There are at least three general approaches to this.
First, use an index instead of an iterator:
vector<int> getConcatenation(vector<int>& nums) {
int size = nums.size();
for (int i = 0; i < size; ++i)
nums.push_back(nums[i]);
return nums;
}
Second, use an iterator but ensure that the vector doesn't have to reallocate:
vector<int> getConcatenation(vector<int>& nums) {
int size = nums.size();
nums.reserve(2 * size);
auto itr = nums.begin();
while (--size)
nums.push_back(*itr++);
return nums;
}
(and that approach includes less labor-intensive things like using a builtin algorithm that copies based on iterators)
Third, unless you have to modify the input argument, just build a vector that's the right size and copy into it:
vector<int> getConcatenation(const vector<int>& nums) {
vector<int> result(2 * nums.size());
std::copy(nums.begin(), nums.end(), result.begin());
std::copy(nums.begin(), nums.end(), result.begin() + nums.size());
return result;
}
push_backcan invalidate all iterators. en.cppreference.com/w/cpp/container/vector/push_back You could use indices instead or reserve enough space so reallocation isn't required.