Vector Assign Function - C++ Programming Tutorial
C++ Course / STL Vector / Vector Assign Function

Vector Assign Function

BLUF: Mastering Vector Assign Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Vector Assign Function

C++ is renowned for its efficiency. Learn how Vector Assign Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

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.

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.

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:

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.

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience