I am trying to understand vectors and assign(). I am following syntax of vectorname.assign(int Num, int value)
Below is the sample code. To my understanding 'value' will be assigned to 'Num' of elements in a vector. My query is why after assign() even the size() of container is getting changed. This should occur only when my container is small and the 'Num' is greater. Please correct me if I am wrong in my understanding.
int main()
{
cout << endl << "---- assign() on already ----" << endl;
// Assign vector
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << "Size : " << v.size() << endl;
cout << "Capacity : " << v.capacity() << endl;
cout << "The vector elements are: ";
for (int i = 0; i < v.size(); i )
cout << v[i] << " ";
cout << endl;
// fill the array with 10 five times
v.assign(5, 10);
cout << "Size : " << v.size() << endl;
cout << "Capacity : " << v.capacity() << endl;
cout << "The vector elements after assign() using size() are: ";
for (int i = 0; i < v.size(); i )
cout << v[i] << " ";
cout << endl;
return 0;
}
CodePudding user response:
std::vector::assign
replaces the content of the vector.
See here: std::vector<T,Allocator>::assign
Therefore the following line replaces the current content of v
with 5 elements of value 10.
v.assign(5, 10);
This is why the size()
is changes from 9 to 5.
The capacity however does not have to change. The capacity relates to the size of the actual block of memory that was allocated to store the vector's elements. It can be equal or greater than the number of actual elements.It was 9 and can stay 9. You can use std::vector::shrink_to_fit
to attempt to reduce the allocated memory.
But as you can see here: std::vector<T,Allocator>::shrink_to_fit,
It depends on the implementation whether the request is fulfilled.
CodePudding user response:
fuction assign() will release the old memory totally, and request a new memory section, the new size is 'Num', then copy the the 'value' to every element to the new memory.
CodePudding user response:
Replaces the contents with
count
copies of valuevalue
.
void print(std::vector<int>& v){
std::cout << "size " << v.size() << "\n";
for(auto& i: v)
std::cout << i << " ";
std::cout << "\n";
}
int main(){
std::vector<int> vec(10, 2);
print(vec);
// size 10
// 2 2 2 2 2 2 2 2 2 2
vec.assign(5, -1);
print(vec);
// size 5
// -1 -1 -1 -1 -1
vec.assign(15, 3);
print(vec);
// size 15
// 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
}
If you want to fill N values of your vector with a value from the given start point use std::fill_n
int main(){
std::vector<int> vec(10, 2);
print(vec);
// size 10
// 2 2 2 2 2 2 2 2 2 2
std::fill_n(vec.begin(), 5, -1) // Fills first 5 values with -1
// size 10
// -1 -1 -1 -1 -1 2 2 2 2 2
std::fill_n(vec.begin(), 15, 3); // Error. Since going out of bounds.
}