vector::assign function


The assign function of vector assign values to the vector.There are three versions of assign function in vector.

T: Data type of the vector

1 void assign(size_t n, const T& val);
2 template<typename IT> void assign(IT first , IT last);
3 void assign(initializer_list<T> l );(C++11)

Each of these functions vary little in how they can be used.A detail description of each of these functions is provided below.



void assign(size_t n, const T& val);

This function copies a value to the vector a specified number of times.

Parameters:
n – An unsigned type value which specify the number of times the value should be copied to the vector.

val – A value to be assigned to the vector.

Return type
void

Note in using this function if the vector hold any values previously ,they are overwritten.

Code example:

vector<int> vec ;

vec.assign( 2 , 678 ); ///Copies 678 two times in vec

for ( auto elem:vec )
{
cout<< elem << ” , ” ;
}

Output,

678 , 678

Here is another example where the vector gets overwritten with the new value when the function is called.

vector<int> vec={ 34 , 45 } ;

cout<< vec.size( ) << endl ;

vec.assign( 4 , 99 ); ///assign vec with 99 four times

for ( auto elem:vec )
{
cout<< elem << ” , ” ;
}

cout<< vec.size( ) << endl ;

Output,

2
99 , 99 , 99 , 99
4

The previous values are overwritten and even the size of the vector is changed.






template<typename IT> void assign(IT first , IT last);

This version of assign function is called when you copy a range of values from another container.

Parameters:
first – An iterator or pointer signifying the starting position of the range to be copied.

last – An iterator which determine the end of range

Return type
void

The range of value copied is [first ,last) ;the last value is excluded.

Code example:

vector<string> vecSt={ “Vector”, “Assign” } ,
vecSt1 ;

vecSt1.assign( vecSt.begin() , vecSt.end() ); ///Copies all the value of ‘vecSt’ into ‘vecSt1’

for ( auto elem:vec1 )
{
cout<< elem << ” ” ;
}

Output

Vector Assign

Here is another code example,where a pointer is passed to determine the range of values to be copied.

int arr[ ]={ 23 , 89 , 45 } ;

vector<int> vec1 ;

vec1.assign( arr , arr+2 );

for ( auto elem:vec1 )
{
cout<< elem << ” , ” ;
}

Output,

23 , 89 ,

The value pointed by ‘arr+2‘ i.e arr[2] value is not copied.


 


Stop wasting time,earn money($$$) from your website-Join Now!


void assign(initializer_list<T> l );

This last version assigns vector with the values taken from the initializer_list.

Parameters:
l – An initializer_list object.

Return type
void

All the values of the intializer_list is copied into the vector.The size of the vector is equal to the number of values copied .The old data of the vector is lost.

Code example:

initializer_list< string> l={ “New” , ” string” , ” copied.” };

vector<string> vecSt ={ “Happy!” };

vecSt.assign( l );

for ( auto elem:vecSt )
{
cout<< elem ;
}

Output

New string copied.