C++ Vector assign
This function updates the vector by assigning new values and replacing the existing ones.
Syntax
Consider a vector v to which a value needs to be assigned. The syntax for this operation is:
v.assign(first,last);
v.assign(n,val);
Parameter
It establishes the range where "first" represents an input iterator indicating the initial element, while "last" signifies an input iterator pointing just beyond the final element.
n : Number of times the value to be occurred.
It specifies the value that will be assigned.
Return value
It does not return any value.
Example 1
Let's see a simple example.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
vector<int> v1;
v1.assign(v.begin()+1,v.end()-1);
for(int i=0;i<v1.size();i++)
std::cout<<v1[i] <<std::endl;
return 0;
}
Output:
In this instance, a vector named v, which holds integer values, is assigned to another vector called v1 utilizing the assign method.
Example 2
Let's see a another simple example.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<char> v;
v.assign(5,'C');
for(int i=0;i<v.size();i++)
std::cout<< v[i] << " ";
return 0;
}
Output:
C CCCC
In this instance, the value 'C' is assigned to variable v five times by employing the assign function.
Example 3
Let's see a simple example.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<char> v{'C','+','+'};
vector<char> v1;
v1.assign(v.begin(),v.end());
for(int i=0;i<v.size();i++)
std::cout<< v[i];
return 0;
}
Output:
In this instance, a vector v that holds character values is assigned to vector v1 using the assign method.