I wrote a program to insert the numbers in C++ with CLion.
First, enter a set of positive integers and place them into the vector called pour. Then, take the negative numbers of these positive integers and then emplace them into the pour. However, when I tried to use the range-based for loop to insert the negative numbers into the pour, the last element always gave a random number without any reason. But once I don't use the range-based loop, the last element won't give me a random number.
#include <iostream>
#include <vector>
using namespace std;
int n , m ;
vector<int> pour ;
int main()
{
for (int i=0 ; i<3 ; ++i)
{
cin >> m ;
pour.emplace_back(m) ;
}
for (auto i : pour)
{
pour.emplace_back(-i) ;
}
for (auto i : pour)
{
cout << i << endl ;
}
return 0;
}
As one of the comments suggests, this question talks about the difference between the number of elements in a vector and the capacity of the vector. The capacity is the number of elements that the vector could hold, not the number it actually holds. You can append elements to the vector (with
push_backoremplace_back) until the vector hits its capacity and the vector won't need to reallocate its storage, so iterators and pointers to its elements remain valid. That's the key here: adjust the capacity so that you can work through the initial elements of the vector and append the new values without triggering a reallocation.So, once you've got the initial elements into
pour, adjust its capacity so that it's large enough for the insertions, and then do them:This puts the new elements at the end of the vector. If the task is to put the negation of each element immediately after the element (e.g., 1, -1, 2, -2), the bookkeeping is a bit more tricky, but the principle is the same: adjust the size first, then iterate through the initial elements and put in the new values.