English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ vector assign() usage and example

C++ Vector (Container)

This function assigns new values to the vector (vector) and replaces the old values.

Syntax

The vector (vector) 'v' to be assigned values. Syntax is:

v.assign(first, last);
v.assign(n, val);

Parameters

(first, last): It defines the range. Assigns the elements of the interval (first, last) to the current vector container.

n: It defines the number of occurrences of the value.

val: It defines the value to be assigned.

Return value

It does not return any value.

Example1

Let's look at 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:

2
3
4

In this example, the vector containing integer values (vector) 'v' is assigned to the vector (vector) 'v' using the assign() function1.

Example2

Let's look at another simple example.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<char> v;
v.assign(5C');
for(int i = 0; i < v.size(); i++)
std::cout << v[i] << " ";
return 0;
}

Output:

C CCCC

In this example, the 'C' value is assigned to 'v' five times using the assign() function.

Example3

Let's look at 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:

C++

In this example, the vector v containing character values is assigned to the vector v using the assign() function1.

C++ Vector (Container)